在Angular2 +和leaflet.js中管理函数和变量范围的问题

时间:2018-04-10 07:38:37

标签: angular leaflet

我想知道是否以及如何访问Map.on事件处理函数内部组件中的全局变量

HTML

<div #map id="map"></div>

组件

private ready = false;

export class HelloComponent implements OnInit {


  constructor(private _signalR: SignalR,
    private service: CustomerTrackingService) { }

  ngOnInit() {

    const layer = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
      // attribution: 'Map data &copy; <a href='http://openstreetmap.org'>OpenStreetMap</a> contributors, <a href='http://creativecommons.org/licenses/by-sa/2.0/'>CC-BY-SA</a>, Imagery © <a href='http://mapbox.com'>Mapbox</a>',
      maxZoom: 23,
      id: 'mapbox.streets',
      accessToken: <TOKEN>
    });


    this.map = L.map('map', {
      center: [34.037008, -84.533377],
      zoom: 18,
      layers: [layer, this._floorplan_layer, heatmapLayer]
    });


    let draw = true;
    this.map.on({
      movestart: function () { draw = false; },
      moveend: function () { draw = true; },
      click: function () { this.ready = !this.ready }
      },
      mousemove: function (e) {
        if (this.ready && draw) {
          //DRAW
        }
      }
    });    
  }    
}

我使用变量ready并绘制以启用和禁用绘图。 draw 是ngOnit()中的局部变量,其中ready是组件的全局变量。但是在map.on函数内部, this.ready 的值未定义。我将 ready 保留为全局变量,因为我希望能够在外部切换值,就像使用map div之外的按钮单击一样。

1 个答案:

答案 0 :(得分:0)

感谢@kaddath,得到了答案。我能够将组件上下文作为变量存储在我的ngOnInit()内部,并将其用作全局变量的参考。

ngOnInit() {
    let context = this;
    let draw = true;
    this.map.on({
      movestart: function () { draw = false; },
      moveend: function () { draw = true; },
      click: function () { context.ready = !this.ready }
      },
      mousemove: function (e) {
        if (context.ready && draw) {
          //DRAW
        }
      }
     });    
}
相关问题