Wednesday, February 13th, 2008

Extending dojo.query()

Category: CSS, Dojo, JavaScript

Alex 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:

javascript

  1. dojo.NodeList.prototype.inspect = function(){
  2.     this.forEach("console.debug(item.innerHTML);");
  3.     return this;
  4. }
  5.  
  6. // now we can call it:
  7. dojo.query("#container > p").inspect();
  8.  
  9. // or via a direct instance:
  10. var nl = new dojo.NodeList(dojo.byId("container"), document.body);
  11. 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:

javascript

  1. // this file located in:
  2. //    acme/ext-dojo/NodeList.js
  3.  
  4. dojo.provide("acme.ext-dojo.NodeList");
  5. // require() statements go here
  6.  
  7. dojo.extend(dojo.NodeList, {
  8.     inspect: function(){
  9.         this.forEach("console.debug(item.innerHTML);");
  10.         return this;
  11.     },
  12.     ...
  13. });

Posted by Dion Almaer at 2:36 am
Comment here

+++--
3.5 rating from 19 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.