0

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.

2

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

0

The 'this' context is a feature. Upon a click event e.target will hold a layer and in order to get the feature you can access e.target.feature inside your click function. No need to bind in my opinion.

onEachFeature: function(feature,layer){
        console.log(this) // context is here(containing all needed f() & variables 
        layer.on({
            click: function(e){
                    var clicked_layer = e.target;
                    var clicked_feature = e.target.feature;
                }
         })
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.