Mucking Dijit

Ever so often I want Dijit to behave just slightly different than the defaults, or need
to shim some added checks or setup to existing methods in the dijit. There are three really rapid ways to easily customize the Dijit code, each with different results and different use cases. Enter dojo.extend, dojo.mixin, and dojo.declare.


Expanding on a simple setTitle dijit.Dialog extension on the Dojo Forums. The example uses dojo.extend to directly modify the Dialog’s prototype, giving the setTitle method to any and all Dialogs created in the page:

dojo.require("dijit.Dialog");
dojo.extend(dijit.Dialog,{
     setTitle: function(/*string*/title){
         this.titleNode.innerHTML = title || "";
     }
});

The second method would give a setTitle method to a particular instance of a Dialog, using dojo.mixin to “mix” the method into the object, or in this case instance:

dojo.require("dijit.Dialog");
dojo.addOnLoad(function(){
     var dialog = new dijit.Dialog({ title:"test" });
     dialog.startup();
     dojo.mixin(dialog,{
          setTitle:function(title){
               this.titleNode.innerHTML = title || "";
          }
     });
});

the third and most configurable way: “subclassing” (or more literally, inherting) via dojo.declare.

dojo.provide("my.Dialog");
dojo.require("dijit.Dialog");
dojo.declare("my.Dialog",dijit.Dialog,{
     setTitle:function(title){
          this.titleNode.innerHTML = title || "";
     }
});

This creates a new widget named my.Dialog leaving the actual dijit.Dialog unmodified, and without having to know which instance you want to have a setTitle method.
You can also use this technique to override default dijit behavior by mixing/extending a method with an existing name.

Finally, if you want to simply “add code” to an existing method, you simply call the inherited() method:

dojo.require("dijit.Dialog");
dojo.declare("my.Dialog",dijit.Dialog,{
     canBeShown: true,
     // extend the default show() method
     show:function(){
            if(this.canBeShown){
                    this.inherited(arguments);
            }
     }
});

now you can set .canBeShown = false on any my.Dialog instance, and the three new lines will prevent the “original” show() method from executing. You must pass the arg: “arguments” to inherited() so the superclass has a way of knowing the name of the function which called it (arguments.callee)

Tags: ,