Login Register

Publish and Subscribe Events

Use publish and subscribe to communicate events anonymously between widgets or any JavaScript functions of your choosing. You may also consider customizing the widget to allow the topic name to be passed in as an initialization parameter to make the widget more flexible.

The following example shows how two objects may use publish and subscribe to communicate with each other.

var foo = new function() {
    this.init = function() {
        dojo.event.topic.subscribe("/mytopic", this, processMessages);
    }

    function processMessages(message) {
        alert("Message: " + message.content);
   }
}

var bar = new function() {
    this.showMessage = function(message) {
        dojo.event.topic.publish("/mytopic", {content: message});
    }
}

foo.init();
bar.showMessage("Hello Dojo Master");

In the exampe above the object foo registers with a topic called '/mytopic' when the init function is called. Bar publishes a message to the topic '/mytopic' which results in the function showMessages being called. You can create any number of topics to publish and subscribe to.



Using publish and subscibe is very easy and it makes wiring things together easy. Widget communication by default is within the same JavaScipt execution context. Not all event handling need be exposed using publish and subscribe however using these types of events allows your code to be flexible and permit future integration with other widgets.