1

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/

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Alejandro García Iglesias
  • 16,222
  • 11
  • 51
  • 64
  • I had the same problem. Here's the way to go, even if this thread is probably dead... http://stackoverflow.com/questions/2689010/mootools-programmatically-fired-events-not-working-with-event-delegation?rq=1 – zhealot Sep 10 '12 at 20:58

3 Answers3

2

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/

Alejandro García Iglesias
  • 16,222
  • 11
  • 51
  • 64
  • When the **option** in **select** is changed manually **this** inside handler function refers to the **select** element. – Diode Dec 19 '11 at 19:47
  • @Diode, Yes but I'm not talking about clicking the select and selecting the option with the mouse. I'm talking about firing the event throug JS. Thanks anyway. – Alejandro García Iglesias Dec 20 '11 at 18:07
0
$$('.country').addEvent('change', function(){

    console.log(this);
    // "this" refers to select

    console.log(this.getElement(':selected'));
    // this.getElement(':selected') refers to selected option

}).fireEvent('change');
Diode
  • 24,570
  • 8
  • 40
  • 51
-1

This may be what you are after... I picked this up in the IRC over a year ago and can't tell you who provided it.

http://jsfiddle.net/prbNK/7/

and an Element method for better code reuse - http://jsfiddle.net/prbNK/12/

Kirk Bentley
  • 243
  • 1
  • 7