本文介绍了Leaflet-marker单击事件工作正常,但类的方法在回调函数中未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码将回调函数添加到单击事件中以获取一些传单标记(我不知道其先验数字):

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 抛出运行时错误n说:

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:

这是一个在类中声明的函数,我用它来显示带有自定义消息的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.

在JavaScript中并不一定是指你的班级实例对象。当函数被称为时,它是上下文

你可以用,在许多图书馆中,您也可以轻松强制它。在这种情况下,使用Leaflet,您可以将第三个参数传递给:

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)

这篇关于Leaflet-marker单击事件工作正常,但类的方法在回调函数中未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 11:51