Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

Event Delegation with MooTools

12 Responses »

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="http://davidwalsh.name">David Walsh Blog Link 1</a></li>
	<li><a href="http://davidwalsh.name">David Walsh Blog Link 2</a></li>
	<li><a href="http://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:'http://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!

Discussion

  1. October 27, 2009 @ 9:13 am

    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()…

  2. October 27, 2009 @ 9:15 am

    @Chris the Developer: Fair enough — let me know if you decide to create your own version. Our ears are always open! Thanks!

  3. October 27, 2009 @ 1:50 pm

    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

  4. October 27, 2009 @ 4:30 pm

    Element.implement({

    delegateEvent: function(type, rules, prevent, propagate){
    return this.addEvent(type, function(e) {
    var event = new Event(e);
    var target = document.id(event.target);
    var prevent = prevent || false;
    var propagate = propagate || true;

    for (var selector in rules) {
    if (target.match(selector)) {
    if (prevent) event.preventDefault();
    if (!propagate) event.stopPropagation();
    if (rules[selector].apply) return rules[selector].apply(target, $A(arguments));
    }
    }
    });
    }
    });

  5. October 27, 2009 @ 4:31 pm

    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! :)

  6. October 27, 2009 @ 7:06 pm

    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…

  7. October 28, 2009 @ 4:41 am

    Also, just to be clear, my approach allows you to delegate different functions for different selector matches, in the same setup:

    document.id(‘container’).delegateEvent(‘click’, {
    ‘.headings’: function() {
    console.log(‘heading clicked’);
    },
    ‘.intro’: function() {
    console.log(‘intro clicked’);
    }
    });

    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.

  8. October 28, 2009 @ 4:49 am

    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

  9. October 30, 2009 @ 2:52 am

    <> .

  10. November 2, 2009 @ 9:45 am

    @Dimitar Christoff: Yes.

    @Chris the Developer: Not bad! I’ll pass this onto the team and see what they have to say!

  11. jay
    November 5, 2009 @ 10:38 am

    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’) ?

  12. November 6, 2009 @ 3:00 am

    @jay – click:relay(input[type=button])

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!