Leaflet- marker click event works fine but methods

2019-01-15 21:01发布

问题:

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)