Event Delegation with MooTools
Events play a huge role in JavaScript. I can't name one website I've created in the past two years that hasn't used JavaScript event handling on some level. Ask yourself: how often do I inject elements into the DOM and not add an event to them? For me it's very rare. For this reason I'm proud and excited for the release of MooTools 1.2.4's Event.Delegation code.
WTF is Event Delegation?
Event delegation is the process of assigning an event listener to a parent for all of its children instead of assigning the same event to every child.
Some Sample HTML
<ul id="link-list"> <li><a href="https://davidwalsh.name">David Walsh Blog Link 1</a></li> <li><a href="https://davidwalsh.name">David Walsh Blog Link 2</a></li> <li><a href="https://davidwalsh.name">David Walsh Blog Link 3</a></li> </ul>
A list with 3 list item elements which contain a link. For the sake of my example, this list will have list items added to it and we want an alert to pop up any time a link within the list is clicked.
The MooTools JavaScript Event Delegation Syntax
window.addEvent('domready',function() { /* delegate */ document.id('link-list').addEvent('click:relay(a)', function(e){ e.stop(); alert('you clicked a link!'); }); /* Add link to show event delegation works! Notice how we haven't assigned an event to this specific element. We already added the event to the list element itself */ document.id('add-link').addEvent('click',function() { var li = new Element('li').inject('link-list'); var link = new Element('a',{ text:'David Walsh Blog', href:'https://davidwalsh.name'}).inject(li); }); });
All you need to do is add :relay to the parent selector and place the "children" match inside the relay pseudo selector. You'll probably question how :relay works because the ":" syntax is used for pseudo selectors. The Element.Delegation JavaScript download overwrites the addEvent, removeEvent, and fireEvent methods to accommodate for the :relay syntax.
Event Delegation Replaces...
var links = document.id('link-list').getElements('li'); links.each(function(link) { link.addEvent('click',function() { //assign actions here }); })
Why collect and iterate through elements to add events when you can simply use event delegation?
Event delegation is a great way to avoid repeating the same event assignments for elements within a parent element, especially when you are adding elements into the page dynamically. If you've not upgraded to MooTools 1.2.4 yet, I hope this is just the kick in the pants you need!
Event delegation is the shizzle, but I’m not a fan of how it’s done in MooTools. It’s great that it’s in there, but I feel that the functionality should be contained in its own method.
I get that both assign events to the same element, but click:relay(selector) is not the most intuitive approach. I’m more for passing an object literal with the selector as key and the method as value, kind of like addEvents()…
@Chris the Developer: Fair enough — let me know if you decide to create your own version. Our ears are always open! Thanks!
I forgot all about this being added. Great stuff. Now when I pull html back from a request and I need to add events to it, no need to do collection.removeEvent collection.addEvent
Good grief…some mistakes in that one though. Like the 4 separate var statements and the new Event(e) nonsense…But you get the idea! :)
Writing a function for this like Chris_the_Developer proposed is IMHO more intuitive and easier to handle.
I didn’t really got the point with the “:relay” pseudoselector…
Also, just to be clear, my approach allows you to delegate different functions for different selector matches, in the same setup:
Which means you can have 2 behaviors on 1 event. I don’t see how that’s possible with the relay event…I imagine you would have to add relay twice, which means 2 events for 2 behaviors.
is this similar to the infamous .live() in jquery? have you also seen this implementation:
http://www.k1der.net/country/mootools/live-events-demo.html
<> .
@Dimitar Christoff: Yes.
@Chris the Developer: Not bad! I’ll pass this onto the team and see what they have to say!
So… what if you want to do click:relay( ‘a specific element, eg an input button – not a submit btn, but an input btn’ )
in the above scenario what would ‘x’ be in click:relay(‘x’) ?
@jay – click:relay(input[type=button])
Hey there!
I would like to know w(tf)hat if I need to apply it only to some tags inside parent element but only certain, not everyone? (of course every link has a unique id… but suppose links within parent element are about 50…)
Chris’s method is cleaner, more powerful, and more intuitive.
Much more “moootools”.
Any reason why it didn’t fly? Delegation is now in the core, at v1.4
And how do you fire that event with fireEvent() ? I can’t get it to work!
Ok, got it:
fireEvent('change:relay(element)')
But I noticed that
this
now refers to the parent element… How can I get the child element reference inside the callback?Here’s a StackOverflow: http://stackoverflow.com/questions/8565225/mootools-event-delegation-how-to-reference-child-element-inside-callback/8565640#8565640
Your code
is a little over complicated – it could easily be replaced with