Search code examples
javascriptasp.net-web-apienyo

Behavioral difference between enyo.dispatch(e) and target.dispatchEvent(e) web api


I am curious to know that how dispatch of event happens in Enyo. Say for a, simple DOM tree, having a parent node with two child nodes. All i want to do is to propagate custom event generated from child 1 to child 2. I have created a sample for this.

http://jsfiddle.net/hfh3z2q4/

enyo.kind({
name: "MySample",
kind: "moon.Panels",
classes: "moon",
pattern:"activity",
components: [{kind: "moon.Panel", 
title: "Hello World!",headerComponents: [
{kind: "moon.IconButton", src: "assets/icon-like.png"}
], 
components: [
{kind: "moon.Input",placeholder: "type time",onchange :"handleInput"},
{kind:"ClockSample", name:'time'}
]}
],
handleInput: function(inSender, inEvent) {
    // body...
    var val=inSender.getValue();
    var evt = document.createEvent("Event");
    evt.initEvent("myEvent",true,true);
    evt.val=val;
    var target=this.$.time.hasNode();
    target.dispatchEvent(evt);
    //enyo.dispatcher.dispatch(evt);
}
});
enyo.kind({
name: "ClockSample",
components: [
    {kind: "moon.Clock", name:"clock"}
],
create:function(){
    this.inherited(arguments);
    enyo.dispatcher.listen(document, "myEvent",  this.bindSafely(this.myEventHandler));
},
myEventHandler: function(inSender, inEvent) {
    // body...
    this.$.clock.setDate(new Date(inSender.val));
}
});


new MySample({fit:true}).renderInto(document.body);

If i try to use "target.dispatchEvent(evt)", and type the expected date format (i.e. Jan 01 2015 09:08:07), the clock time will set to the same, but the behavior is not similiar when try to use "enyo.dispatcher.dispatch(evt)".

Please help me to know the differences and enyo way of achieve the same.


Solution

  • Let me start by saying 'Don't do that!'. This is not the correct way to handle this type of problem. If you really must send messages like this between objects use signals. To attempt to send messages between siblings breaks encapsulation.

    Second, Enyo's normal events aren't DOM events. If you want to create events on objects to listen for you should declare an events block with your events, as described here: Event Handling. You've gone down the DOM event route, which I don't recommend. If you do want to use DOM events, then use the dispatchEvent() method you've already taken.

    Third, when using Moonstone, only select Dark or Light, not both. Moonstone requires the use of the Spotlight library, as well.

    Finally, using dispatcher.dispatch() bypasses the dom event registration you did with listen(). You can overcome that using signals and listening for the custom event. But really, just use pure signals. Try this fiddle for the first (less ideal) approach: http://jsfiddle.net/hfh3z2q4/1/