I’m terribly sorry for asking yet another anonymous-function question, but it seams like every time I figure them out, javascript throws me another curve ball.
I am using KineticJS to create a number of circles then animate them like so (following these tutorials )
for ( i = 0; i < rows; i++ )
{
for ( j = 0; j < cols; j++ )
{
index = i * cols + j;
circles [ index ] = new Kinetic.Circle({...});
...
}
}
...
for ( i = 0; i < rows; i++ )
{
for ( j = 0; j < cols; j++ )
{
index = i * cols + j;
anims [ index ] = new Kinetic.Animation({func: function ( frame )
{
( function ( innerCircle )
{
...
} ( circles [ index ] ) );
},
node: layer
}
);
}
}
My intention is to pass the current value of index when creating the anonymous function. Problem is that only the last image is being animated and I can’t figure out why. Here is the full jsfiddle
Your function that is supposed to create a new variable scope is in the wrong place. It shoudl be outside the function being passed, and should return a new function.
The returned function will have access to the desired value.
But honestly, don’t inline functions like this. It becomes so much clearer when you make a named function that returns your function.
Some people just love those inlined functions for some reason, but I think they just add clutter. A named function breaks up the code a bit, and adds a little documentation to the code.
Also, it’s slightly more efficient because you’re not making a new inlined function in every iteration of the loop. Instead you’re reusing the same one to build the handler.