我正在使用以下代码为某些传单标记(我事先不知道其编号)的 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
正确打印标记的 lat
和 lng
的值,但是在调用 displayError
抛出一个运行时错误说:
this.displayError is not a function
这是在类中声明的一个函数,根据我的需要,我用它来显示带有自定义消息的 toast 。这是代码:
displayError(messageErr: string) {
let toast = this.toastCtrl.create({
message: messageErr,
duration: 3000,
position: 'top'
});
toast.present();
}
为什么说那不是函数?
编辑:不仅仅是displayError
,类的每个函数都会给出这个消息。
最佳答案
这是一个典型的 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));
还有 arrow function解决方案,它使用 this
的上下文/值箭头函数定义的地方,而不是它将被调用的地方:
marker.on('click', (event) => this.markerClick(event));
关于javascript - Leaflet- 标记点击事件工作正常,但类的方法在回调函数中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48170860/