Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  106] [ 6]  / answers: 1 / hits: 30816  / 11 Years ago, tue, february 26, 2013, 12:00:00

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!


More From » dom

 Answers
20

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);
}

[#79994] Monday, February 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makaylahk

Total Points: 166
Total Questions: 94
Total Answers: 117

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;