I have code that looks like this:
for( var i=0; i<10; i++ ) {
var someClickableObject = new Object();
someClickableObject.index = i;
eventListenerFunction(someClickableObject, 'click', function() {
alert(someClickableObject.index);
});
}
So I am creating a bunch of clickable objects, giving each a property equal to the loop index, setting a click event on the object which alerts its index property.
I want each object to alert the index i in which it was created. Instead all the objects alert 9. I think this is because the event listener forms a closure over the object which gets redefined on each iteration.
Any ideas on how to solve this?