0

I got a problem when I try to set EventListenr for each DOM object inside an array. the function that I define for each DomEvent becomes the same for all of them (console.log(key) prints the same key(last key in loop) for all of the items). my code is like this:

var dom = {};
var popupContent = L.DomUtil.create('div');
for(var key in this._info){
    dom[key] = L.DomUtil.create('a', "", popupContent);
    dom[key].innerHTML = key;
    dom[key].href = "#";
    L.DomEvent.on(dom[key], 'click', function(){
        //do some stuff
        console.log(key);
    });         
 }

var popup = L.popup();
popup.setLatLng(latlng)
      .setContent(popupContent)
      .openOn(this._map);

Thank you in advance for any help you can give me :)

mohammad fatemi
  • 327
  • 2
  • 15

1 Answers1

1

The problem here is with closure function inside of your loop.

You can fix it like this:

for(var key in this._info){
  (function(k) {
    dom[k] = L.DomUtil.create('a', "", popupContent);
    dom[k].innerHTML = key;
    dom[k].href = "#";
    L.DomEvent.on(dom[k], 'click', function(){
      //do some stuff
      console.log(k);
    });
  })(key)
}

Or you can just use let instead of var inside your loop.

For more information check this question.

Sergii Rudenko
  • 2,603
  • 1
  • 22
  • 24