Leaflet- marker click event works fine but methods of the class are undefined in the callback function(Leaflet-标记点击事件工作正常,但回调函数中未定义类的方法)
问题描述
我正在使用以下代码为一些传单标记(我不知道其中的数字)的 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
这是一个在类中声明的函数,我用来根据我的需要显示带有自定义消息的 toast.这是代码:
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-标记点击事件工作正常,但回调函数中未定义类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Leaflet-标记点击事件工作正常,但回调函数中未定


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01