Thursday, February 21st, 2008
Motionbox EventHandler: Event Subscription and Delegation
The developers of MotionBox have written a custom Prototype.js based library to handle event delegation and they decided to open source their work.
They told me:
As you know, the technique of listening to events high in the DOM adds a lot of benefits. The two most notable are:
- The ability to bind to events before the elements are available in the DOM. This is especially useful for AJAX applications where the DOM is being updated as there is no need to (re)create all your observers. Using this library, the developer doesn't care if an element exists or not, he/she can simply say "any thing with this class works this way" and "anything with this ID does this" All with a simple interface:
MBX.EventHandler.subscribe("#myId", "click", myHandlerFunction); - Since we handle events outside of the usual manner, custom event handling becomes trivial. The subscription interface is exactly the same, and custom events can be fired easily with:
MBX.EventHandler.fireCustom(domElement, "my_custom_event_name");
Given the following doc:
You can do the following:
-
-
MBX.EventHandler.subscribe("#one", "click", my_listener); // this will trigger 'my_listener' only by clicking on the li with the id of "one"
-
-
MBX.EventHandler.subscribe(".my_li_class", "click", my_listener); // this will trigger 'my_listener' by clicking either of the LIs below
-
-
MBX.EventHandler.subscribe([".my_ul_class", "#one"], ["click", "mouseover"], [my_listener, my_second_listener]);
-
-
// Custom events
-
MBX.EventHandler.subscribe("#one", "my_custom_event_name", my_listener);
-
-
// Fire them
-
MBX.EventHandler.fireCustom($("one"), "my_custom_event_name");
-
You can get this from SVN or download it directly.
To see it in action, check out Motionbox.com (used a lot on contests and Motionbooks pages --login required).













Thanks for the great post Dion. Hope everyone finds the EventHandler as useful as we have. Comments are always appreciated if anyone sees a way to make it better.
This is very similar to the Reg library Sun is working on.
http://blogs.sun.com/greimer/entry/a_look_at_our_new.
i love this and will be using this model in the future. thanks
We fixed a bug in the code that could cause headaches for some people.
The new direct download link is here:
http://motionbox.googlecode.com/files/event_handler-1.0.1.js
Swish, very swish. Nice approach, I can see myself using this heavily in a couple of web apps I’m writing. Good job.