MooTools - software-activated events that do not work with event delegation

It would be very helpful if someone could help me figure out why I cannot programmatically fire events when using event delegation in MooTools (from the Element.Delegation class).

There is a parent <div> that has a change listener for some child <input> elements. When a change event is triggered by user actions, the handler in the parent div fires, but when I fire it programmatically using fireEvent on any child input, nothing happens. Basic setting:

HTML

 <div id="listener"> <input type="text" id="color" class="color" /> ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​</div>​​​​​​​​​​​ 

Js

 $("listener").addEvent("change:relay(.color)", function() { alert("changed!!"); }); $("color").fireEvent("change"); // nothing happens 

The event handler in the parent div is not called. Any help is appreciated. Hooray!


Related question: do events triggered with a fireEvent bubble generally fireEvent in the DOM tree? My current hack is to send the event initially, but it works (but the hack, nonetheless) - http://jsfiddle.net/SZZ3Z/1/

 var event = document.createEvent("HTMLEvents") event.initEvent("change", true); document.getElementById("color").dispatchEvent(event); // instead of fireEvent 
+7
javascript mootools javascript-events event-delegation
source share
2 answers

it will not work too well as it is. The problem with bubbling events (and programmatically triggering events) is that the event object may require a β€œreal” one to contain event.target , which maps to the relay string. In addition, document.id("color").fireEvent() will not work because the color itself is not bound to it.

to get around this, you fake the event on the parent listener by passing in an event object that contains the target element as follows:

 document.id("listener").fireEvent("change", { target: document.id("color") }); 

view in action: http://www.jsfiddle.net/xZFqp/1/

if you are doing something like event.stop in your callback function, you need to pass {target: document.id("color"), stop: Function.from} , etc. for any event methods that you can reference, but the event delegation code is only interested in target .

+15
source share

I solved it like this:

 document.addEvents({ 'click:relay(.remove_curso)': function(){ document.fireEvent('_remove_curso', this); }, '_remove_curso':function( me ){ console.log( me ); }.bind( this ) } 
0
source share

All Articles