0

I have an event handler which calls the selectContinents() function:

var map = {
    eventHandler: function() {
        events.on('continentsChangedDropdown', (continents) => this.selectContinents(continents));
    },
    selectFeature: function(layer) {
            //selects feature;
    },
    unselectFeature: function(layer) {
            //unselects feature;
    },
    selectContinents: function(continents) {
        geojson.eachLayer(function(layer) {
            var continent = layer.feature.properties.continent;
            if (continents.includes(continent)) {
                this.selectFeature.bind(this, layer);
            }
            else {
                this.unselectFeature.bind(this, layer);
            }
        });
    }
};

which in turn calls either selectFeature() or unselectFeature().

However this returns

map.js:105 Uncaught TypeError: Cannot read property 'bind' of undefined

I understand this in this in bind(this) doesn't refer to the map object, but I don't know how to access the map object.

KSS
  • 147
  • 1
  • 8

1 Answers1

0

Use arrow function instead. They keep the enclosing scope:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

geojson.eachLayer((layer) => {
    var continent = layer.feature.properties.continent;
        if (continents.includes(continent)) {
            this.selectFeature.bind(this, layer);
        }
        else {
            this.unselectFeature.bind(this, layer);
        }
    });
Roberto Zvjerković
  • 9,657
  • 4
  • 26
  • 47
  • It now doesn't call the select/unselectFeature() methods. There is no error message though. – KSS Mar 27 '19 at 14:36