Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function call inside loop taking only last iteration

my code look like this:

if (ACTIVETICKETS.length > 0) 
{
    for (var m in  ACTIVETICKETS) 
    {
        if (ACTIVETICKETS.hasOwnProperty(m)) 
        {
            var marker = new L.Marker(new L.LatLng(ACTIVETICKETS[m].location.x, ACTIVETICKETS[m].location.y));
            createHtmlForPopUp(m, function(data)
            {
                console.log(m);
                marker.bindPopup( data ); // calling a function with callback
                tile_layer.addLayer(marker);                           
            });
        }
    } // for loop ends here
}

While executing this, I am getting only the last iteration of m. Total length of ACTIVETICKETS array is 16. So I am getting only 15 entered 16 time

like image 226
Akbar Ali Avatar asked Sep 13 '26 18:09

Akbar Ali


1 Answers

The code below should work, but as I commented above, please read about closure so you know why.

    if (ACTIVETICKETS.length > 0) {
      for (var m in  ACTIVETICKETS) {
        (function(x) {
          if (ACTIVETICKETS.hasOwnProperty(x)) {
            var marker = new L.Marker(new L.LatLng(ACTIVETICKETS[x].location.x, ACTIVETICKETS[x].location.y));
              createHtmlForPopUp(x, function(data){
                console.log(x);
                marker.bindPopup( data ); // calling a function with callback
                tile_layer.addLayer(marker);
              });
          }
        })(m);
      } // for loop ends here
    }
like image 57
Tyler Biscoe Avatar answered Sep 15 '26 06:09

Tyler Biscoe