How to pass arguments to addEventListener listener function?


How to pass arguments to addEventListener listener function?

The situation is somewhat like-
var someVar = some_other_function();
someObj.addEventListener(“click”, function(){
}, 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.


Solution 1:

There is absolutely nothing wrong with the code you’ve written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous

function() { some_function(someVar); } 

was created.

Check if the alert gives you the value you’ve been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar variable next to the call to addEventListener)

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

Solution 2:

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


var someInput = document.querySelector('input');
someInput.addEventListener('click', myFunc, false);
someInput.myParam = 'This is my parameter';
function myFunc(evt)
  window.alert( );

JavaScript is a prototype-oriented language, remember!

Solution 3:

This question is old but I thought I’d offer an alternative using ES5’s .bind() – for posterity. 🙂

function some_func(otherFunc, ev) {
    // magic happens
someObj.addEventListener("click", some_func.bind(null, some_other_func), false);

Just be aware that you need to set up your listener function with the first param as the argument you’re passing into bind (your other function) and the second param is now the event (instead of the first, as it would have been).

Solution 4:

You can add and remove eventlisteners with arguments by declaring a function as a variable.


newSrc is the method with myaudio as parameter
funcName is the function name variable

You can remove the listener with

Solution 5:

Quite and old question but I had the same issue today. Cleanest solution I found is to use the concept of currying.

The code for that:

someObj.addEventListener('click', some_function(someVar));

var some_function = function(someVar) {
    return function curried_func(e) {
        // do something here

By naming the curried function it allows you to call Object.removeEventListener to unregister the eventListener at a later execution time.

Solution 6:

You can just bind all necessary arguments with ‘bind’:

root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));

In this way you’ll always get the event, arg1, and other stuff passed to myPrettyHandler.