Leaflet- marker click event works fine but methods of the class are undefined in the callback function
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);
With bind
it would be:
marker.on('click', this.markerClick.bind(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));