I\'ve seen programmers assign events listeners inside loops, using the counter. I believe this is the syntax:
for(var i=0; i < someArray.length; i++){
some
The (function(i))(i)
syntax creates an anonymous function and then immediately executes it.
Usually you'll do this to create a new function every time through the loop, that has its own copy of the variable instead of every event handler sharing the same variable.
So for example:
for(int i = 0; i < 10; i++)
buttons[i].click = function() { doFoo(i); };
Often catches people out, because no matter what button you click on, doFoo(10)
is called.
Whereas:
for(int i = 0; i < 10; i++)
buttons[i].click = (function(i){ return function() { doFoo(i); };)(i);
Creates a new instance of the inner function (with its own value of i
) for each iteration, and works as expected.