【问题标题】:Ionic/Leaflet.js : How can I call a function from the L.Draw.Event.CREATED event?Ionic/Leaflet.js:如何从 L.Draw.Event.CREATED 事件中调用函数?
【发布时间】:2018-05-21 20:31:24
【问题描述】:

我正在使用 Leaflet Draw 在地图上绘制简单的形状。创建形状后,我想调用另一个方法。

我正在收听这样的CREATE 事件:

drawMap() {
    this.myMap = L.map('map', {
        crs: L.CRS.Simple
    });

    ...

    this.myMap.on(L.Draw.Event.CREATED, function (e) {
      let type = e.layerType;
      let layer = e.layer;

      this.myOtherMethod();  // this.myOtherMethod is not a function

      drawLayer.addLayer(layer);
    });
}

myOtherMethod() {
    console.log('hello world!');
}

如果我从事件监听器中取出this.myOtherMethod();,它会调用它,所以我知道这是一个范围问题。我不确定如何调用父作用域。

感谢您的任何建议!

【问题讨论】:

    标签: ionic2 leaflet.draw


    【解决方案1】:

    不要使用匿名函数作为回调,而是创建一个单独的命名函数,然后可以调用myOtherMethod

    drawMap() {
        this.myMap = L.map('map', {
            crs: L.CRS.Simple
        });
    
        ...
    
        this.myMap.on(L.Draw.Event.CREATED,this.onCreate.bind(this) );
    }
    
    onCreate (e) {
          let type = e.layerType;
          let layer = e.layer;
    
          this.myOtherMethod();  // this.myOtherMethod is not a function
    
          drawLayer.addLayer(layer);
    }
    
    
    myOtherMethod() {
        console.log('hello world!');
    }
    

    【讨论】:

    • 你先生 - 太棒了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    相关资源
    最近更新 更多