- The Book of Dojo
- The Dojo Book, 0.4
- Part 1: "Introduction"
- Part 2: "Out of the Box" Dojo
- Part 3: "The Dojo Programming Model"
- Part 4: "More on Widgets"
- Part 5: "Connecting the pieces"
- Part 6: "Customizing Dojo Builds for Better Performance"
- Part 7: "Utilities"
- Part 8: "Internationalization and Accessiblity"
- Part 9: "Dojo Community"
- Part 10: "Fresh From The Shed" Dojo
- BookWriting
- Glossary
Topics
Submitted by bill on Thu, 08/10/2006 - 10:46.
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.