How to pass an argument to a listener function passed in addEventListener?

anItem.addEventListener("click", iRespond, false); 

The problem is that I need to pass an iRespond argument, since iRespond is supposed to handle clicks on many elements, and I need a way to distinguish between elements.

How can i do this?

+1
source share
3 answers

Simple closure:

 var foo = "bar"; e.addEventListener('whee',function(evt){ iRespond(evt,foo); },false); 

If a simple closure fails (because you snap a variable that changes, for example, in a loop), you need to create a new closure on this value:

 foo.addEventListener('bar',(function(jim){ return function(evt){ iRespond(evt,jim); // Surprise surprise, jim is available here! } })(someValueToBeNamedJim), false); 

For instance:

 var buttons = document.querySelectorAll('button'); for (var i=buttons.length;i--;)} buttons[i].addEventListener('click',(function(j){ return function(){ alert("You clicked on button #"+j); }; })(i),false); } 

You can choose a variable name both inside and outside the function without permission - using i instead of j above - but you may run into confusion.

+3
source

There are many possibilities. No1 will create a closure for him. You can also use bind() .

A better solution might be to distinguish between parameters (per element) using the target property of the event, which is also passed to the listener. This will become very elegant if you use only one handler for many elements, for example. adding it to <ul> instead of one for each <li> element. Then choose what to do, for example, using the identifiers or data attributes of the target element.

+1
source

No one seems to offer the simplest solution. Put your other function call in an anonymous function as follows:

 anItem.addEventListener("click", function() { iRespond(your arg here); }, false); 

Or in many cases, you can simply specify the this pointer in the event listener to find out which object you were called from:

 anItem.addEventListener("click", iRespond, false); 

Then in iRespond :

 function iRespond() { // this points to the item that caused the event so you can // determine which one you are processing and then act accordingly // For example, this.id is the id of the object } 
+1
source

Source: https://habr.com/ru/post/1203813/


All Articles