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

前端 未结 1 732
执念已碎
执念已碎 2020-11-27 23:02

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):



        
相关标签:
1条回答
  • 2020-11-27 23:38

    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)
    
    0 讨论(0)
提交回复
热议问题