Modules
Once you get started writing Dojo code, you'll start writing more sophisticated client side code. And the more code you write, the more you will split into JavaScript modules. The more files, the more dangerous are the consequences of using JavaScript carelessly. For example, a harmless little function like this:
sum = 0;
for(i in listOfNumbers){
sum += listOfNumbers[i];
}
return sum / listOfNumbers.length;
}
tucked away in a script will wreak havoc on the following in another script:
var retval = 0;
for(i in listOfNumbers){
retval += listOfNumbers[i];
}
return retval;
}
document.print(avg(a));
document.print(sum(a));
Because the variable sum in the avg function is stored in the global namespace (i.e. it is not prefixed by "var"), it will overwrite the loaded sum() function in the second script. This leads to hard-to-diagnose errors
What you need is to keep these modules corralled in their own spaces. While modularization is not part of JavaScript, Dojo can simulate it for you through namespaces. And you've been using them all along! Whenever you execute a dojo.require, you are invoking a module loaded into its own namespace. So, for example, dijit.Toolbar is a namespace. Java and C# have similar constructs named packages.
While namespaces are optional, they tend to lessen hassles down the road as your code base grows.
- Printer-friendly version
- Login or register to post comments
- Subscribe post