Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments to addEventListener listener function?

The situation is somewhat like-

var someVar = some_other_function(); someObj.addEventListener("click", function(){     some_function(someVar); }, false); 

The problem is that the value of someVar is not visible inside the listener function of the addEventListener, where it is probably being treated as a new variable.

like image 472
Abhishek Yadav Avatar asked Nov 02 '08 10:11

Abhishek Yadav


People also ask

Which arguments can be passed into the addEventListener method?

With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter: addEventListener(event, function, useCapture); The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.

What is the third argument in addEventListener?

addEventListener listens for both capture phase and bubbling phase events. The third parameter (called useCapture in the specification) allows the programmer to specify which phase they want to use. In modern browsers, this defaults to false .


1 Answers

Why not just get the arguments from the target attribute of the event?

Example:

const someInput = document.querySelector('button');  someInput.addEventListener('click', myFunc, false);  someInput.myParam = 'This is my parameter';  function myFunc(evt)  {    window.alert(evt.currentTarget.myParam);  }
<button class="input">Show parameter</button>

JavaScript is a prototype-oriented language, remember!

like image 166
Zaloz Avatar answered Sep 30 '22 11:09

Zaloz