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
This is invalid:
arr[i].el.addEventListener('click', do_something(arr[i]));
The listener must be a function reference. You cannot specify parameters 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 your listener into an anonymous 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);
To have access 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);
}