Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add event listeners to an array of objects

Tags:

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} 
like image 782
Ryan Williams Avatar asked Jul 31 '13 21:07

Ryan Williams


People also ask

Can you add an event listener to an array of elements?

To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document. querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.

How do I add multiple events listener?

The addEventListener() method You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.

Can you add event listeners to DIVS?

To add a click event listener on div tag using JavaScript, we can call the addEventListener method on the selected div. to add a div with a class. Then we write: const div = document.


1 Answers

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.

like image 181
Sushanth -- Avatar answered Sep 20 '22 10:09

Sushanth --