Tuesday 25 September 2012

Dojo Topic

Dojo provides a really useful topic based messaging system that can be used to send messages between decoupled pieces of javascript.

require / define

To use the topic functionality just include

    "dojo/topic"

at the top of the javascript file in the require or define section


Subscribe / Publish

It is really easy to use this functionality.  Firstly subscribe to a topic where the topic has a particular string name and a function to call as a result of a message,


    topic.subscribe("/log/add", function(message) {
        console.log(message);
    });


Now everytime a publish is done to the /log/add topic the function will be called.

To publish to that topic

    topic.publish("/log/add", "the message");

The publish subscribe isn't limited to one variable and can be passed multiple values.

That's really all there is to it.  The functionality is incredibly useful for larger web apps and particularly where the app code has been split into different modules and not all modules know about each other.  It helps to keep the hierarchy correct.


No comments:

Post a Comment