When I add an event listener like so: oTarget.addEventListener(sEventType, fnHandler, false); how can I send some attributes to the fnHandler function?
A:
Use a wrapper function like:
oTarget.addEventListener(sEventType, function(evt) {
return fnHandler(evt, "foo", "bar");
}, false)
Now you’re passing an anonymous function (the wrapper function) that calls fnHandler with the listed attributes and returns the value to where that callback function is called.
Gumbo
2010-02-05 14:28:06
Where does the return go?
meouw
2010-02-05 14:32:01
@meouw: It depends on what the caller does that calls the callback function.
Gumbo
2010-02-05 14:59:19
@Gumbo - but what happens in this particular case, the return isn't accessible is it? I always thought event handlers were void
meouw
2010-02-05 15:33:47
@meouw: I'm with you. `return` is redundant here. It is ignored as per DOM spec: http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener It's libraries like jQuery that make the `return` value of an event listener meaningful (as a convenience to `stopPropagation()` and `preventDefault()`).
Roatin Marth
2010-02-05 15:53:40
A:
You can can create an anonymous function that passes the additional parameters:
oTarget.addEventListener(sEventType, function(e) {
myFunction(e, attr2, attr3);
}, false);
Chris Pebble
2010-02-05 14:29:39
Anonymous functions work as long as you don't need to remove the listener at some point.
Tim R
2010-02-05 14:51:54
How would I then remove the listener that used an anonymous function as a callback function?
Frank Furd
2010-02-05 14:57:47
@Frank: unless you saved a reference to the anonymous function *somewhere*, you will not be able to remove it.
Roatin Marth
2010-02-05 15:50:33