[GIS] how to bind data to Layer.on in leaflet

javascriptleaflet

I have the following :

onEachFeature: function(feature,layer){
        console.log(this) // context is here(containing all needed f() & variables 
        layer.on({
            click: function(e){

                }
         })
 }

I want to access the this context inside the click event click. I tried to bind(this) with layer.on.bind(this) but didn't work. So comes my question how can access to value stored in the higher context.

Best Answer

.bind() applies to a function, even an anonymous one, so:

L.geoJson(data, {
  onEachFeature: function(feature, layer){
    layer.on({
      click: (function(ev){
        // Whatever
      }).bind(this)
    })
  }
});

This defines an anonymous function(function(ev) {...}), then gets its closure by doing (function(ev) {...}).bind(this).