2005/12/01

The only cross-platform way to add dynamically parameterized events to DOM elements:

To explain what I mean. This is static:
<div onclick="foo()">...</div>
This is dynamic, unparameterized:
div.setAttribute("onclick", "foo()"); //not in IE6

//or:

div.onclick = foo; // works everywhere
This is dynamic, parameterized (and works on Mozilla):
div.setAttribute("inclick", "foo(this, 1, 2, 3, 'bar')")
This allows you do do stuff like construct your function as you would a string. But you can't do div.onclick = foo; and pass arguments as well. So you have to do this:
div.onclick = function() { foo(this, 1, 2, 3, "bar"); };
Which basically creates an anonymous function each time it's evaluated. If you want to construct your function call as a string, do that and then use eval(). (I would also add that if you have to do that here, you have bigger problems than dynamically parameterized events.) But hey, it works.

You might wonder why I'm passing this when I could use the event target instead. First, getting the event target is non-cross platform, and second, I might want to do foo( $("id") ...), which again is more cross-platform than fireEvent or whatever.

No comments: