Motionbox EventHandler: Event Subscription and Delegation
Date : 2008 02 21 Category : Tech & DevelopmentThe 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:
PLAIN TEXT HTML:<script>
function my_listener(evt) {
console.dir(evt);
}
</script>
<body>
<ul id="unordered_list" class="my_ul_class">
<li id="one" class="my_li_class">First</li>
<li id="two" class="my_li_class">Second</li>
</ul>
</body>
You can do the following:
PLAIN TEXT JAVASCRIPT: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).
