Wow, what a sexy title!
This little function will allow you specify multiple event handler functions for any javascript event using the object.event (traditional) event registration method. (see http://www.quirksmode.org/js/introevents.html for more on javascript events).
Why? Well, often you want to register multiple handlers for the same event, where one dynamic html page might be split across multiple files. A good example would be an ASP.NET page and the user controls which make up that page. You might want to do something against window.onload in the main page and also in a part of the page where this code is in a different file. Without the extra eventAddHandler function below it's not possible to register more than one function in different locations.
i'm heavily indebted to Simon's article on this http://simon.incutio.com/archive/2004/05/26/addLoadEvent of which this code is an extension.
This code has been tested in Firefox 1.0, IE 6.02, Opera 7.5 on PC and IE 5.01, IE 5.2 and Safari 1.2 on the Mac. I've no reason to believe it won't work on any browser that supports Javascript 1.2 as i'm not doing anything particularly browser specific in the event registration.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head><script type="text/javascript">
// event worker object constructorfunction EventWorker(){ this.addHandler = EventWorker.addHandler;}
// event worker static methodEventWorker.addHandler = function (eventRef, func) { var eventHandlers = eval(eventRef); if (typeof eventHandlers == 'function') { // not first handler eval(eventRef + " = function(event) {eventHandlers(event); func(event);}"); } else { // first handler eval(eventRef + " = func;"); } }
// use EventWorker to add window.onload and 2 btnClick events// note: calls to EventWorker.addHandler can be made anywhere on the page
EventWorker.addHandler("window.onload", function() { EventWorker.addHandler("btnClick.onclick", test1); EventWorker.addHandler("btnClick.onclick", test2); });
function test1(e){ displayEventDetails(e); alert("success 1");}
function test2(e){ displayEventDetails(e); alert("success 2");}
function displayEventDetails(e) { if (!e) e = window.event; alert(e.type); // event type}
</script></head><body>
<input type="button" value="Click me" id="btnClick" />
</body></html>
Powered by: newtelligence dasBlog 1.9.6264.0
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2010, Keith Patton
E-mail