Dean
Dean

Reputation: 255

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?

Upvotes: 3

Views: 1356

Answers (2)

Eduardo Matos
Eduardo Matos

Reputation: 741

If you want to publish/subscribe global events, you may find dojo/topic helpful.

Upvotes: 1

phusick
phusick

Reputation: 7352

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/

Upvotes: 3

Related Questions