Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :-)

like image 370
WheresWardy Avatar asked Oct 20 '10 14:10

WheresWardy


People also ask

Can an anonymous function have parameters?

An anonymous function is a function with no name which can be used once they're created. The anonymous function can be used in passing as a parameter to another function or in the immediate execution of a function.

Are anonymous functions closures?

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.

Can you pass anonymous function as an argument to another function?

Summary. Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.

Can we assign an anonymous function to a variable in JavaScript?

An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.


1 Answers

You can access i directly from you anonymous function (via closure), but you need to capture it so that each call to geocode gets its own copy. As usual in javascript, adding another function will do the trick. I renamed the outer i variable to make it clearer:

for(var iter = 0; iter < 5; iter++) {
    (function(i) {
        geocoder.geocode({'address': address}, function(results, status) {
            // Geocoder stuff here
            // you can freely access i here
        });
    })(iter);
}
like image 192
Gabe Moothart Avatar answered Oct 03 '22 16:10

Gabe Moothart