Leaflet-标记点击事件工作正常,但回调函数中未定义类的方法 [英] Leaflet- marker click event works fine but methods of the class are undefined in the callback function

查看:20
本文介绍了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 正在正确打印标记的 latlng 的值,但是在调用 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-标记点击事件工作正常,但回调函数中未定义类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆