0

I have read this answer but still have a headache on making the code work.

I have a slightly different needs. Instead of alerting I have to bind each object. My code is:

for (var i = 0; i < markers_length; i++) {
    events_number = data.markers[i].events_number //data.markers is a multidimentional array
    marker = L.marker([ data.markers[i].latitude , data.markers[i].longitude ]); //just create the new object
    marker.on('mouseover', function(){
        return function(){
            this.bindPopup(" Found"+events_number+" event(s)").openPopup();
        }
    }(i) );
}

I am using leaflet if you ask. For a single object the bindPopup would work like:

marker.on('mouseover', this.bindPopup('hi').openPopup());

The trouble is that the above code gives the last object for all the. I assume that there is a problem with the this and the level of the functions. So how can I bind each marker with a separate text?

Community
  • 1
  • 1
Diolor
  • 13,181
  • 30
  • 111
  • 179

1 Answers1

3

it should be:

marker.on('mouseover', function(en){
    return function(){
        this.bindPopup(" Found"+en+" event(s)").openPopup();
    }
}(events_number) );

You have to pass the value that you want to be saved in the closure (events_number in this case), and the function has to take a parameter to receive that value and use it in the closure (en in my code).

Barmar
  • 741,623
  • 53
  • 500
  • 612