Extending dojo.query()
Date : 2008 02 13 Category : Tech & DevelopmentAlex Russell has taken some time to share the path you take when you go the Dojo Way and “build with, not on”. He posted an example of how to extend dojo.query() which walks through the steps:
Step 1: grok dojo.NodeList
dojo.NodeList is the Array subclass which all dojo.query() calls return an instance of. Therefore, to extend the results of a dojo.query(), we really want to extend the dojo.NodeList class. Both dojo.query() and dojo.NodeList are available as soon as dojo.js is included in your page.
Step 2: extend NodeList the old-skool way
Instances of dojo.NodeList pick up properties from the prototype object of the dojo.NodeList class. Lets add an inspect() method which logs out the innerHTML of the nodes in the list to the Firebug console:
PLAIN TEXT JAVASCRIPT:dojo.NodeList.prototype.inspect = function(){
this.forEach("console.debug(item.innerHTML);");
return this;
}
// now we can call it:
dojo.query("#container> p").inspect();
// or via a direct instance:
var nl = new dojo.NodeList(dojo.byId("container"), document.body);
nl.inspect();
Step 3: modernize and package it up
Lets add a provide() so that we can require() our module and use a bit of Dojo’s language tools to extend dojo.NodeList more tersely:
PLAIN TEXT JAVASCRIPT:// this file located in:
// acme/ext-dojo/NodeList.js
dojo.provide("acme.ext-dojo.NodeList");
// require() statements go here
dojo.extend(dojo.NodeList, {
inspect: function(){
this.forEach("console.debug(item.innerHTML);");
return this;
},
...
});