greg606
greg606

Reputation: 491

javascript: access to a loop counter in nested callbacks

I'm trying to get access to a lopp index in nested callbacks. Here is the code:

gatherAddresses: function(){
    var divs = $('#searchResults .address');
    var addrs = [];
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].className == 'address') {
            var address = $.trim($(divs[i]).html());
            var rel = divs[i].getAttribute('rel');
            results.addresses.push({
                address: address,
                rel: rel
            });
            results.geocoder.getLatLng(address, function(point){

                if (!point) {
                    alert(address + ' not found');
                }
                else {
                    var marker = new GMarker(point);

                    //chmurka :) 
                    GEvent.addListener(marker, "click", function(){

/////////////here I want the loop index

                        marker.openInfoWindowHtml("<b>""</b><br/>");
                    });
                    results.map.addOverlay(marker);
                    addrs.push({
                        rel: results.findRel(address),
                        point: point
                    });
                    results.findCenter(addrs, results.map);


                }
            });
        }
    }
},

I know it's all about understanding callbacks and variables scopes but I ask for your help since it's my first callback problem :)

Upvotes: 0

Views: 1105

Answers (2)

Ivo Wetzel
Ivo Wetzel

Reputation: 46756

Your callback already has access to i due to closures, but it has a "reference" to the variable, so the value might not be the one you want, since it will always be the latest and greatest, if you want the callback to use the value if i when results.geocoder.getLatLng was called you need to create a copy of i via another, anonymous function:

(function(e) { // get a copy of the value that WON'T change
  GEvent.addListener(marker, "click", function(){
     // use e here as the index
  });
})(i); // pass the value of i in

Upvotes: 3

Tomalak
Tomalak

Reputation: 338326

GEvent.addListener(marker, "click", function (loopIndex) {
  return function () {
    // the variable "loopIndex" will have the value of i
    marker.openInfoWindowHtml("<b>""</b><br/>");
  }
}(i));

Upvotes: 1

Related Questions