dojo.subscribe

Status:Draft
Version:1.0
Available:since 0.9

Linked a listener to a named topic.

Introduction

Subscribe is a part of the the Dojo Topic system used to register a function listening to a named channel. The channel is sent data via dojo.publish.

Usage

To subscribe a function to a channel:

1
2
3
 dojo.subscribe("/foo/bar/baz", function(data){
    console.log("i got", data);
 });

To trigger that function, publish some data on the same channel:

1
 dojo.publish("/foo/bar/baz", [{ some:"object data" }]);

The channel name can be any string you choose:

1
2
3
 dojo.subscribe("foo-bar", function(data){ /* handle */ });
 dojo.subscribe("bar", function(data){ /* handle */ });
 dojo.subscribe("/foo/bar", function(data){ /* handle */ });

Each are unique channels.

Globbing

Dojo Topics do not support globbing, or mixing of channel names based on wildcards. This example is invalid:

1
 dojo.subscribe("/foo/*", function(data){ /* handle */ });

While this works when using cometd's dojox.cometd.subscribe function, it is not practical to do on the client side. Only fully named channels are supported.

Subscribing with scope

Subscribe uses dojo.hitch under the covers to provide more advanced functionality for controlling in which context the attached function will be called.

Consider the following object:

1
2
3
4
5
6
 var obj = {
    member:"unpublished",
    anon: function(data){
        this.member = "fixed";
    }
 }

To execute an anonymous function in the scope of obj:

1
2
3
4
 dojo.subscribe("/foo/bar", obj, function(data){
     // here 'this' refers to the obj instance
     this.member = "published";
 });

Alternately, you can pass a named function instead of an anonymous function with scope:

1
 dojo.subscribe("/foo/bar", obj, "anon");

This will execute obj.anon() in the scope of obj, passing in whatever data the accompanying dojo.publish call sent.

Error in the documentation? Can’t find what you are looking for? Let us know!