开发者

puzzle: value in clousure is changed

I use http://tile.cloudmade.com/wml/latest/web-maps-lite.js to geocode.

There is a address array containing around 20 addresess

addresses[n] = {where:where,who:who,contact:contact,note:note,type:type};

Then I loop the array to geocode

for (var i = 0; i < addresses.length; i++) {
    geocoder2.getLocations(addresses[i].where, function(response) { //a callback
       return function(k){
       Lat[k] = response.features[0].centroid.coordinates[0];
       Lng[k] = response.features[0].centroid.coordinates[1];
       latlng = new google.maps.LatLng(Lat[k], L开发者_JAVA百科ng[k]);
        MarkerArray[k] = new google.maps.Marker({
          map: map,
          position: latlng,
          zIndex: k,
          title: addresses[k].who,
          icon: icons(addresses[k].type.trim())
        });}(i) // a closure function called
    });
}

But the it always works on the final index. Why??


You have the Closure Loop Problem. You appear to be trying to fix it by adding the return function(k)... closure, but that's all occurring inside the callback function, so it won't execute until the loop has exited and i is pointing at its final value.

You would have to push that wrapper out a level so it's directly inside the loop:

for (var i = 0; i < addresses.length; i++) {
    geocoder2.getLocations(addresses[i].where, function(k) { //a callback
        return function(response){
            Lat[k] = response.features[0].centroid.coordinates[0];
            Lng[k] = response.features[0].centroid.coordinates[1];
            latlng = new google.maps.LatLng(Lat[k], Lng[k]);
            MarkerArray[k] = new google.maps.Marker({
                map: map,
                position: latlng,
                zIndex: k,
                title: addresses[k].who,
                icon: icons(addresses[k].type.trim())
            });
        }
    }(i)); // binding *here* instead!
}

Or use Function#bind to avoid the nested function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜