如何将事件侦听器添加到对象数组 [英] How to add event listeners to an array of objects
问题描述
我有一组对象(特别是 easelJS
个图像)-像这样:
I have an array of objects (specifically easelJS
images) - something like this:
var imageArray = new Array;
gShape = new createjs.Shape();
// shape is something
imageArray.push(gShape);
我要做的是使用事件监听器,而不是:
What I want to do is have an event listener instead of:
gShape.addEventListener("click", function() {alert"stuff"});
我希望程序明确知道单击了哪个区域,以便我可以在以下方式:
I want the program to know specifically which region is clicked so that I can send an alert box in the following way:
imageArray[index].addEventListener("click", function(){
alert " you clicked region number " + index}
推荐答案
当然。使用闭包保存该迭代的索引,否则将由同一函数作用域共享,并为您提供同一迭代的值。为每个函数创建一个单独的函数会将其状态保存在函数内部。
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);
}
或更佳
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进行救援
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);
});
}
使用 let
关键字在迭代中为变量创建一个块作用域,并且在调用事件处理程序时将具有正确的索引。
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.
这篇关于如何将事件侦听器添加到对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!