Dojo Toolkit, require and events.

Written by - Saumya

14 January 2015

Well, lets say this, if you are working on Dojo Toolkit, you are working on a legacy application. Since Dojo Toolkit is releasing its newer versions, you need to change your application to newer codebase. Currently Dojo Toolkit is leveraging AMD for modules and Javascript files. Which is very new for this toolkit and veteran developers in this toolkit may find its very different.

Previously, when we needed some JS code, its simply done by making a ‘require’ call.

dojo.require("dojo.string");
//then use it
dojo.string.trim("  I Like Trim Strings ");

Now it looks as

require(["dojo/string", "dojo/domReady!"], function(string){
  string.trim("  I Like Trim Strings ");
});

Well that may seems fine now, but then what happens when we need something inside that require itself? Actually, its simpler than it seems, we can have require inside another require too.

require(["dojo/domReady!"], function(){
    //DOM is ready, load another module
    require(["dojo/string"], function(string){
      string.trim("  I Like Trim Strings ");
    });
});

Thats nice. Here is the official documentation. The introduction to modern dojo is here.
Another nice utility is topic. This is kind of central event dispatching and listening station. All one has to do is, dispatch events through topic and listen through it too. These are called publish and subscribe of events.

require(["dojo/topic"], function(topic){
    topic.subscribe("some/topic", function(arguments){
        console.log("received:", arguments);
    });
    // ...
    topic.publish("some/topic", "one", "two");
});

The other kind of events are DOM events and they are handled with the ‘on’ module.

Happy coding.