Dojo – Using Query, forEach, and Connect

I recently created a help system for a Dojo application that I have been working on. I wanted a simple implementation, but also one that is fairly robust. My initial implementation (version 1) was easy to create due to the power of dojo.query, dojo.forEach, and dojo.connect.

I first created a ‘help’ link for each section of the application. All links have the same class, “stepHelp”. I use the ‘title’ attribute to distinguish the help ‘categories’.

<h3>Meta Data <a href="#" class="stepHelp" title="metaData">(help)</a></h3>
<h3>Site Colors <a href="#" class="stepHelp" title="siteColors">(help)</a></h3>
<h3>Intro Text <a href="#" class="stepHelp" title="introText">(help)</a></h3>
...

For version 1 of this system, I created an associative array to store each help description. In my next version, I will create a separate html page for each category and use the Dojo’s contentPane href attribute to dynamically display the contents.
var arHelp = new Array();
arHelp['metaData'] = 'metaData Help';
arHelp['siteColors'] = 'Site Colors Help';
arHelp['introText'] = 'Intro Text Help';
...

In the next version, the array will store the name of the html file instead of the help text.

In the addOnLoad, I call an init function which calls ‘setHelpLinks’. This function uses dojo.query to query ‘a.stepHelp’ and uses dojo.forEach to iterate over each item in the list.

function setHelpLinks() {
     dojo.query("a.stepHelp").forEach(
          function(item, index, array){
               dojo.connect(item, 'onclick', showHelp);
          }
     );
}

As it iterates over each link, it adds an onClick event using dojo.connect. The onClick event calls showHelp:
function showHelp() {
     dojo.byId('help').innerHTML = arHelp[this.title];
     return false;
}

In this version of the help system, the help text is displayed in a div (id = ‘help’). In order to understand the function above, you have to understand event scope. The ‘this’ in ‘this.title’ refers to the ‘<a>’ that was clicked. So if help for ‘metaData’ was clicked, then ‘this.title’ = ‘metaData’. This maps to the associative array: arHelp[‘metaData’] so ‘metaData Help’ will display in the ‘Help’ div. Easy enough. Enjoy.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks