Prototype.js & Event Delegation

an interesting concept in JavaScript is the Event Delegation, which means you use Event Bubbling to delegate events to a parent element. let us take a real world example: you have several elements, that all "fire" the same event. so the idea is to put all of these elements into a parent-container and let the parent-container "fire" the event. in Prototype.js you have the 2 handy functions Event.observe(), which helps you to cleanly set Event Handlers on elements and Event.element() or Event.findElement(), which help you to find out, which element "fired" the event.

this is an Event Handler example:

<ul>
 <li><a href="#" onclick="close_ul();">foo 1</li>
 <li><a href="#" onclick="close_ul();">foo 2</li>
 <li><a href="#" onclick="close_ul();">foo 3</li>
 <li><a href="#" onclick="close_ul();">foo 4</li>
 .... hundreds of list elements ...
</ul>

this is an Event Delegation example:

<ul onclick="close_ul();">
 <li><a href="#">foo 1</li>
 <li><a href="#">foo 2</li>
 <li><a href="#">foo 3</li>
 <li><a href="#">foo 4</li>
 .... hundreds of list elements ...
</ul>

you also could do this directly in JavaScript with Prototype.js' Event.observe(). later in the callback function you can handle the event depending on which element has "fired" it by using Event.element() or Event.findElement(). in a scenario, where you have several nested elements that could all fire the parent event, you can track which element is really "allowed" to "fire".

the advantages might be clear, but here we repeat them: your applications have less code and event handlers, are more stable and faster.

related:
Event Delegation versus Event Handling (example using YUI)
YUI (Yahoo! User Interface Library)

Tuesday, 20. March 2007 • trackback url

Add Comment

( to reply to a comment, click the reply link next to the comment )

Comment Title:
Your Name:
Email Address:
Make Public?
Website:
Make Public?

Comment:


Allowed XHTML tags : a, b, i, strong, code, acrynom, blockquote, abbr. Linebreaks will be converted automatically.


Captcha:

captcha image

please type the content of the above image into the following form-field: