开发者

javascript: access to a loop counter in nested callbacks

开发者 https://www.devze.com 2023-02-02 23:29 出处:网络
I\'m trying to get access to a lopp index in nested callbacks. Here is t开发者_运维问答he code:

I'm trying to get access to a lopp index in nested callbacks. Here is t开发者_运维问答he 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 :)


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


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

精彩评论

暂无评论...
验证码 换一张
取 消