tags:

views:

51

answers:

2

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
Where does the return go?
meouw
@meouw: It depends on what the caller does that calls the callback function.
Gumbo
@Gumbo - but what happens in this particular case, the return isn't accessible is it? I always thought event handlers were void
meouw
@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
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
Anonymous functions work as long as you don't need to remove the listener at some point.
Tim R
How would I then remove the listener that used an anonymous function as a callback function?
Frank Furd
@Frank: unless you saved a reference to the anonymous function *somewhere*, you will not be able to remove it.
Roatin Marth