Login Register

Topics

Dojo provides a means of anynonymous event communication which can be very useful to connect together widgets in a page that may have no previous knowledge of each other. This maybe done using publish/subscribe style events. Publish subscribe style events require that the components that wish to communicate information simply share the name of a topic or queue to which the events are published/subscribed to. Objects may be passed as an argument of the events which provides a powerful means of inter-object/widget communication.

The API for publishing to a topic is as follows:

dojo.event.topic.publish("/topicName", args);

That is pretty much it to publish an event. The arguments are passed as an object literal and will be seen by all clients subscirbed to the corresponding topic "/topicName".



The API for subscribing to a topic is as follows:

dojo.event.topic.subscribe("/scroller", targetObj, targetFunc);

A more detailed example follows:

var ac;

var is;



function init() {

ac = new AccordionMenu();

ac.load();

is = new ImageScroller();

is.load();

}



function Scroller() {

this.setProducts = function(pid) {

// show the products for pid

}



this.handleEvent = function(args) {

if (args.event == 'showProducts') {

this.setProducts(args.value);

}

}



this.load = function () {

dojo.event.topic.subscribe("/scroller", this, handleEvent);

}
function Accordion() {

function expandRow(target) {

...

var link = document.createElement("a");

dojo.event.connect(link, "onclick", function(evt){

this.target = target;

dojo.event.topic.publish("/scroller", {event: "showProducts", value : target});

});

}

}

An "onclick" event on the element link will cause an event to be published to the topic name "/scroller" which is shared by both the Accordion and Scroller objects. In the case of this example the "handleEvent" function of the Scroller object will be callsed with the object literal {event: "showProducts", value : target}.

As can be seen topics can be very useful. When designing widgets or objects that need to interact with widgets or objects consider using publish and subscribe style events.