Leaflet- marker click event works fine but methods of the class are undefined in the callback function

北慕城南 提交于 2019-12-17 14:23:06

问题


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()
})

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")
}

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 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();
}

Why is saying that is not a function?

EDIT: it is not just displayError, every function of the class gives this message.


回答1:


This is a classic JavaScript mistake.

this in JavaScript does not necessarily refer to your class instance object. It is the context of the function when it is called.

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)


来源:https://stackoverflow.com/questions/48170860/leaflet-marker-click-event-works-fine-but-methods-of-the-class-are-undefined-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!