Posts Tagged Dijit

Automatically Require Dijit Widgets

Recently I have been playing with the dojox.dtl: the javascript port of the Django templating engine. So far I am quite impressed, not only is it fast and full featured, but by writing a wrapper class it is easy to make it behave like server side templating systems: you specify a template and pass it an object and it will render that object according to the template rules.

The only trouble I ran into was when I wanted to used Dijit Widgets in my templates. Since on my main page I didn’t know what template I would be calling, I didn’t know which Widget classes to include with dojo.require(). To fix this, I have come up with a little hack that does the job, although not too elegantly.

Bascially my approach includes hooking into dojo.parser and changing its behaviour. Now when it is parsing widgets from the page it checks to see if they exist and, if not, it does the appropriate dojo.require() to try to pull them in.

var fn = dojo.parser.instantiate;
dojo.parser.instantiate = function(nodes){
    dojo.forEach(nodes, function(node){
        var className = node.getAttribute(dojo._scopeName + "Type")
        if(!dojo.isFunction(dojo.getObject(className))){
            //It is not an object... yet
            dojo.require(className);
        }
    });
    return fn(nodes);
}

The above code-block shows the implimentation. Simply place this in between <script> tags in your header. Now you should be able to do dojotypes anywhere on your page and have the appropriate classes automatically included.

There are several disadvantages to my approach. For example, if you have a typo in one of your dojoType, it will try to pull down a file that doesn’t exist. We also have the impact of running through the array of nodes an additional time, although since the dojo.parser.instantiate function is already bounded by O(n) this shouldn’t make a noticeable impact.

, ,

No Comments