Leaflet-marker 单击事件工作正常,但回调函数中未定义该类的方法 [英] Leaflet- marker click event works fine but methods of the class are undefined in the callback function
问题描述
我正在使用以下代码向 click
事件添加回调函数,用于某些传单标记(其中我不知道先验数字):
I'm using the following code to add a callback function to the click
event for some leaflet markers (of which I do not know the number a priori):
newArray.forEach(p => {
let marker = L.marker(latLng).on('click', this.markerClick).addTo(newMap)
marker.bindPopup(content)
marker.addTo(newMap)
marker.openPopup()
})
并且在类中有执行此操作的函数markerClick
:
And in the class there is the function markerClick
that does this:
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
时代码>抛出一个运行时错误说:
The console.log
is printing correctly the values of lat
and lng
of the marker, but when calling displayError
a runtime error is thrown saying that:
this.displayError 不是函数
this.displayError is not a function
这是一个在类中声明的函数,我用来根据我的需要显示带有自定义消息的祝酒词.这是代码:
This is a function declared in class that I use to show a toast with a custom message, accordingly to what I need. This is the code:
displayError(messageErr: string) {
let toast = this.toastCtrl.create({
message: messageErr,
duration: 3000,
position: 'top'
});
toast.present();
}
为什么说那不是函数?
不仅仅是displayError
,类的每个函数都会给出这个消息.
it is not just displayError
, every function of the class gives this message.
推荐答案
这是一个典型的 JavaScript 错误.
This is a classic JavaScript mistake.
this
您可以使用 bind
,并且在许多库中您也可以轻松地强制它.在这种情况下,使用 Leaflet 您可以将第三个参数传递给 on
附加事件侦听器时:
You can force this context with bind
, and in many libraries you can easily force it as well. In this case with Leaflet you can pass a 3rd argument to on
when attaching your event listener:
// 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
的上下文/值箭头函数被定义的地方,而不是它将被调用的地方:
And there is also the arrow function solution, which uses the context / value of this
where the arrow function is defined, rather than where it will be called:
marker.on('click', (event) => this.markerClick(event));
这篇关于Leaflet-marker 单击事件工作正常,但回调函数中未定义该类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!