Adding and Removing Event Listeners with parameters

This is invalid:

arr[i].el.addEventListener('click', do_something(arr[i]));

The listener must be a function reference. When you invoke a function as an argument to addEventListener, the function’s return value will be considered the event handler. You cannot specify arguments at the time of listener assignment. A handler function will always be called with the event being passed as the first argument. To pass other arguments, you can wrap the handler into an anonymous event listener function like so:

elem.addEventListener('click', function(event) {
  do_something( ... )
}

To be able to remove via removeEventListener you just name the handler function:

function myListener(event) {
  do_something( ... );
}

elem.addEventListener('click', myListener);

// ...

elem.removeEventListener('click', myListener);

To have access to other variables in the handler function, you can use closures. E.g.:

function someFunc() {
  var a = 1,
      b = 2;

  function myListener(event) {
    do_something(a, b);
  }
  
  elem.addEventListener('click', myListener);
}

Leave a Comment