Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and Removing Event Listeners with parameters

Tags:

I am writing a vanilla JavaScript tool, that when enabled adds event listeners to each of the elements passed into it.

I would like to do something like this:

var do_something = function (obj) {
        // do something
    };

for (var i = 0; i < arr.length; i++) {
    arr[i].el.addEventListener('click', do_something(arr[i]));
}

Unfortunately this doesn't work, because as far as I know, when adding an event listener, parameters can only be passed into anonymous functions:

for (var i = 0; i < arr.length; i++) {
    arr[i].el.addEventListener('click', function (arr[i]) {
        // do something
    });
}

The problem is that I need to be able to remove the event listener when the tool is disabled, but I don't think it is possible to remove event listeners with anonymous functions.

for (var i = 0; i < arr.length; i++) {
    arr[i].el.removeEventListener('click', do_something);
}

I know I could easily use jQuery to solve my problem, but I am trying to minimise dependencies. jQuery must get round this somehow, but the code is a bit of a jungle!

like image 355
tomturton Avatar asked Feb 26 '13 11:02

tomturton


People also ask

How do you add an event listener to a variable?

To set up an event listener you just need to have a variable that references an element and then call the addEventListener function on that element. This function takes a minimum of two parameters. The first parameter is just a string which is the name of the event to listen to.


1 Answers

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);
}
like image 67
marekful Avatar answered Oct 07 '22 19:10

marekful