Search code examples
jqueryevent-handlingdojojquery-events

Can dojo bind user-defined event?


I use the dojo 1.7 version, I want to bind user-defined event, in jQuery I can do like this:

$(window).bind("pushMessage",function(){});

then trigger the event like this:

$(window).trigger("pushMessage",{});

Can dojo get the same result like above? If yes, how?


Solution

  • Yes, it can via dojo/on:

    on(window, "pushMessage", function(event) {});
    
    on.emit(window, "pushMessage", {
        bubbles: true,
        cancelable: true
    });
    

    See it in action: http://jsfiddle.net/phusick/MQThM/

    There is also dojo/Evented which provides a class that can be used as a base class or mixin for JavaScript classes that emit their own events. An example from documentation:

    require([
        "dojo/_base/declare",
        "dojo/Evented"
    ], function(
        declare,
        Evented
    ) {
    
        var MyComponent = declare([Evented], {
            startup: function() {
                this.emit("ready", {});
            }            
        });
    
        var component = new MyComponent();
        component.on("ready", function() {
            console.log("Component is ready.");        
        });
    
        component.startup();
    
    });​
    

    Also at jsFiddle to play with: http://jsfiddle.net/phusick/ZhG58/