dojo.publish is one of three topic-related functions used to publish (broadcast?) any kind of information within the application, to be received by other functions subscribed to the same channel. A channel can be any string in almost any form you like. Additionally, like other Dojo event functions, a dojo.unsubscribe function is provided to disconnect subscriptions to channels.

Subscribe returns a handle to later be used for disconnecting a subscription, much like the relationship between dojo.connect and dojo.disconnect. Simply pass the handle as the only argument to dojo.unsubscribe to no longer receive updates:

// Dojo 1.7 (AMD)require(["dojo/_base/connect"],function(connect){varhandle=connect.subscribe("/foo/bar",function(message){// only runs once in this case:connect.unsubscribe(handle);});});// Dojo < 1.7varhandle=dojo.subscribe("/foo/bar",function(message){// only runs once in this case:dojo.unsubscribe(handle);});

In the above example, we’re disconnecting the handle from within the subscribed function, effectively creating a “subscribe-once” pattern. After the first time something published on the /foo/bar channel, the connection is interrupted, and the function will no longer fire.

Many other components use this topic mechanism for communication. For instance, Drag and Drop uses the channels /dnd/move/start and /dnd/move/end to publish information about drag operations, and the developer is intended to subscribe to these as needed.

Additionally, the Cometd client implements a variation of publish/subscribe/unsubscribe for it’s communication. The mechanism is identical, though with comet the subscription can exist on other clients on different hosts and domains.

Several Dijit widgets use publish to alert the user (and other internal parts of their operation) about state changes. For instance, any time a new Tab is added to a TabContainer, a message is sent out on a channel based on the id of the Tabs:

// Dojo 1.7 (AMD)require(["dojo/_base/connect"],function(connect){varid="myTabs";connect.subscribe(id+"-addChild",function(child){// child is the new pane being added to the tabs with id="myTabs"});});// Dojo < 1.7varid="myTabs";dojo.subscribe(id+"-addChild",function(child){// child is the new pane being added to the tabs with id="myTabs"});