So, let's say right now you have a list, and your webpage looks a bit like this:
You add a click event to each of the list items.
$$('.list-item').addEvent('click', function(e) {
console.log("You clicked me!");
});
Let's bold these items so we can visualize what's going on, by bolding the ones which will respond to a click event.
Now, if we added a few more items, our list would look like this, since the events are not automatically attached to new elements:
This problem is solved by something called event delegation.
JavaScript events "bubble", which means they continue up through parent nodes of the event target. Since the event target is attached to the event, it then becomes possible to attach events to an outer parent element, which checks to see if the event target matches the chosen selector.
So, instead of attaching a bunch of events, one for each list item, we add a single event to the entire list, which will only fire when a list item has been clicked on.
We can do this using MooTools's event delegation syntax (admittedly not the greatest interface ever).
Let's move our event handler to be on the parent element rather than each item individually.
$('myList').addEvent('click', function() {
console.log("You clicked somewhere on my list!");
}
Now, this will happen even when the user clicks anywhere within the parent, not just on list items. To limit what happens, we use MooTools' event delegation syntax (which is admittedly pretty strange).
$('myList').addEvent('click:relay(.item)', function() {
console.log("You clicked on a list item!");
}
You could also use Eve.js, which is a scoped event delegation framework which runs on top of MooTools.
The code in Eve would look like this:
Eve.scope('#myList', function() {
this.listen('click', '.item', function() {
console.log("You clicked on a list item!");
});
});