Sure. You can just use a closure to save the index of that iteration. Otherwise there are shared by the same function scope and will give you the value of the same iteration. Creating a separate function for each will save the state of that inside the function.
var imageArray = new Array;
gShape = new createjs.Shape();
// shape is something
imageArray.push(gShape); // Dumped all the objects
for (var i = 0; i < imageArray.length; i++) {
(function(index) {
imageArray[index].addEventListener("click", function() {
console.log("you clicked region number " + index);
})
})(i);
}
or better
for(var i = 0; i < imageArray.length; i++) {
imageArray[i].addEventListener("click", bindClick(i));
}
function bindClick(i) {
return function() {
console.log("you clicked region number " + i);
};
}
ES6 to the rescue
let imageArray = [];
gShape = new createjs.Shape();
// shape is something
imageArray.push(gShape); // Dumped all the objects
for (let i = 0; i < imageArray.length; i++) {
imageArray[i].addEventListener("click", function() {
console.log("you clicked region number " + i);
});
}
Using the let
keyword creates a block scoping for the variable in iteration and will have the correct index when the event handler is invoked.
index
wouldn't be correct in the callback – Bignonia