javascript - How to add event listeners to an array of objects -
i have array of objects (specifically easeljs
images) - this:
var imagearray = new array; gshape = new createjs.shape(); // shape imagearray.push(gshape);
what want have event listener instead of:
gshape.addeventlistener("click", function() {alert"stuff"});
i want program know region clicked can send alert box in following way:
imagearray[index].addeventlistener("click", function(){ alert " clicked region number " + index}
sure. can use closure save index of iteration. otherwise there shared same function scope , give value of same iteration. creating separate function each save state of inside function.
var imagearray = new array; gshape = new createjs.shape(); // shape imagearray.push(gshape); // dumped objects for(var i=0; i< immagearray.length; i++) { (function(index) { imagearray[index].addeventlistener("click", function() { console.log("you clicked region number " + index); }) })(i); }
or better
for(var i=0; i< immagearray.length; i++) { imagearray[i].addeventlistener("click", bindclick(i)); } function bindclick(i) { return function(){ console.log("you clicked region number " + i); }; }
Comments
Post a Comment