MooTools event delegation: How to reference child element inside callback?
-
17-04-2021 - |
Question
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/
OTHER TIPS
$$('.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');
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.
and an Element method for better code reuse - http://jsfiddle.net/prbNK/12/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow