Bungow Bungow - 2 months ago 5
Javascript Question

How access class propertys from methods using this keyword

I'm a bit new with javascript and I'm trying to develop a plugin for Leaflet map viewer. I have a class with a options property list, but when i try to access them form "onAdd" method using this keywork is not working.

L.btsControl = L.Control.extend({
options: {
position: 'topright',
//control position - allowed: 'topleft', 'topright',
//'bottomleft', 'bottomright'
minValue: 'isss',
min: 0,
max: 1,
maxValue: '',
},

initialize: function (options) {
L.Util.setOptions(this, options);
},

onAdd: function (map) {
this._map = map;
this._map.eachLayer(function (layer){
if (layer.options.time_i > this.options.max) {
this.options.maxValue = layer.options.time;
}
if (layer.options.time_i < this.options.min) {
this.options.minValue = layer.options.time;
}
});

//SKIPED CODE

return container;
},


So, how can I access min and max properties from onAdd method? now I'm getting "TypeError: this.options is undefined"

The calling function is: var mycontrol = new L.btsControl().addTo(map);

Answer

The callback function you provide to .eachLayer() does not have the context you want. You could resolve this by binding that function to your this:

this._map.eachLayer(function (layer){
    if (layer.options.time_i > this.options.max) {
        this.options.maxValue = layer.options.time;
    }
    if (layer.options.time_i < this.options.min) {
        this.options.minValue = layer.options.time;
    }
}.bind(this));

See Bound invocation and How does the this keyword work.

Comments