Une Bévue wrote:
Hi,
how could i "register" all those methods to the overall one ?
because i don't know, in advance, the methods 1 to n.
One way is to use attachEvent/addEventListener rather than the regular
<obj>.on<event>. Using these two, you can add as many methods as you
want. However, this does not go without problems, as non supporting
agents still require dedicated fallback. Moreover, IE's attachEvent does
not treat correctly the "this" value inside the handler, which may lead
to further issues.
Another basic way consists in simply enclosing the existing handler
within some new handler, using a closure, maybe adjusting the return
value in regards of your needs. The only problem with this approach is
some potential stack overflow if you add numerous listeners (say, many
thousands).
---
<script type="text/javascript">
function addListener(obj, evt, func) {
if(obj[evt]) {
obj[evt]=(function(handler) {
return function() {
handler.call(this, arguments[0]);
func.call(this, arguments[0]);
}
})(obj[evt]);
} else {
obj[evt]=func;
}
}
addListener(window, "onload", function(){alert("1")});
addListener(window, "onload", function(){alert("2")});
</script>
---
Eventually, it is probably better to define your own set of event
management methods, using a custom structure, with its own accessors
(add/remove and not only add), like RobG suggested.
Check out the following script by Lasse Reichstein Nielsen.
<URL:http://www.infimum.dk/privat/eventListener.js>
Ex.:
---
<script type="text/javascript" src="eventListenerLRN.js"></script>
<script type="text/javascript">
EventListener(window);
window.addEventListener("load", function(){alert("1")}, false);
window.addEventListener("load", function(){alert("2")}, false);
</script>
---
aside from that is the "dummy" arg"e" usefull ?
The 'e' argument refers to the event object, which in W3C's compliant
agents is passed as first argument; it may not be necessarily useful for
events such as 'load', however it is essential for events like 'click',
or 'keypress', in which you often have to retrieve event properties to
work some decent effect.
Kind regards,
Elegie.