Search code examples
javascriptmootoolsmootools-events

MooTools event delegation: How to reference child element inside callback?


Having this piece of HTML:

<div id="modal">
    <select class="country">
        <option value=""></option>
        <option value="opt">Opt</option>
    </select>
</div>

And this piece of JS:

$('modal').addEvent('change:relay(.country)', function(){
    console.log(this); // "this" refers to #modal.
}).fireEvent('change:relay(.country)');

Log reveals that the this keyword refers to the #modal element. I want to fire the event for each .country select and have the reference to each one inside the callback. How can I have it? This is the fiddle: http://jsfiddle.net/EWUCG/5/


Solution

  • From chatting on the IRC channel:

    • Event delegation is based off of event bubbling.
    • So the element inside a parent will trigger an event. It will then trigger the events in it's parent node...
    • it does that all the way till there's no more parents (window)
    • So you're really just setting the callback to happen when one of the parents receives the event passed up from it's child.

    The only solution I have left is "eaching":

    $('modal').addEvent('change:relay(.country)', function(event, target){
        console.log(this, event, target); // Then "this" refers to each .country select.
    });
    $$('.country').each(function(el){
        $('modal').fireEvent('change', [null, el]);
    });
    

    Fiddle: http://jsfiddle.net/EWUCG/12/