Attaching parameters with javascript closures to default parameters in anonymous functions

I want to add some extra parameters to the Google geocoder API call as I'm running it in a loop, but am not sure how to append closure parameters to their anonymous function that already has default parameters that are passed in by the call to the API.

For example:

for(var i = 0; i < 5; i++) {
     geocoder.geocode({'address': address}, function(results, status) {
         // Geocoder stuff here
     });
}

I want to be able to use the value of i in the passed geocoder.geocode() anonymous function, but if I had a closure using }(i)); on line 4 for example that would replace the first parameter which would break the geocoder.

Is there a way I can use closures, or pass the value of i into the anonymous function at all?

Effectively what I want to do is:

geocoder.geocode({'address': address}, function(results, status, i) {
    alert(i); // 0, 1, 2, 3, 4
}(i));

but working :-)

5
задан jmac 11 December 2013 в 00:46
поделиться