2

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

Bungow
  • 250
  • 2
  • 10

1 Answers1

1

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 How does the this keyword work.

Graham
  • 6,577
  • 17
  • 55
  • 76
trincot
  • 211,288
  • 25
  • 175
  • 211