Leaflet-marker 单击事件工作正常,但回调函数中未定义该类的方法

IT技术 javascript ionic-framework onclick leaflet gis
2021-01-24 18:08:03

我正在使用以下代码click为某些传单标记(其中我不知道先验数字)事件添加回调函数

newArray.forEach(p => {
  let marker = L.marker(latLng).on('click', this.markerClick).addTo(newMap)
  marker.bindPopup(content)
  marker.addTo(newMap)
  marker.openPopup()
})

在类中有markerClick执行此操作的函数

markerClick(e) {
  console.log("Inside marker click " + e.latlng.lat + "  " + e.latlng.lng)
  this.displayError("You clicked on the marker")
}

console.log正在打印的正确的value观latlng标记,但是打电话时displayError运行时引发错误说:

this.displayError 不是函数

这是在类中声明的函数,我用来根据我的需要显示带有自定义消息的祝酒词。这是代码:

displayError(messageErr: string) {
  let toast = this.toastCtrl.create({
    message: messageErr,
    duration: 3000,
    position: 'top'
  });
  toast.present();
}

为什么说那不是函数?

编辑:它不仅仅是displayError,类的每个函数都给出了这个消息。

1个回答

这是一个典型的 JavaScript 错误。

this在 JavaScript 中不一定是指您的类实例对象。它是函数被调用时上下文

您可以使用 强制此上下文bind,并且在许多库中您也可以轻松地强制它。在这种情况下,使用 Leaflet 您可以on在附加事件侦听器时将第三个参数传递给

// Force current `this` to be the context when `this.markerClick` is called
marker.on('click', this.markerClick, this);

有了bind这将是:

marker.on('click', this.markerClick.bind(this));

还有箭头函数解决方案,它使用this 定义箭头函数位置的上下文/值,而不是将调用它的位置:

marker.on('click', (event) => this.markerClick(event));