As part of the migration I mentioned earlier, I adopted one of the many recipes available on the Internet to start creating a namespace for my common code as well as exclusive namespaces for each project I’m delivering.
The idea is to minimize how much code is available globally as well as to prevent name collisions. It also allows me to isolate my code from some JavaScript frameworks (as I said, I’m still migrating code, so I have both MochiKit and jQuery loaded) or all of them.
if (typeof MainNamespace == "undefined") {
var MainNamespace = {};
}
MainNamespace.namespace = function () {
var a=arguments, o=null, i, j, d;
for (i=0; i<a.length; i=i+1) {
d=a[i].split(".");
o=window;
for (j=0; j<d.length; j=j+1) {
o[d[j]]=o[d[j]] || {};
o=o[d[j]];
}
}
return o;
};
;
The above code is available on a file by itself and its only purpose is to initialize the main namespace for my own code. Since it allows me to create any namespace, I don’t need to replicate that on individual projects.
To use the above, my code looks like this:
(function($) {
MainNamespace.namespace('NewNamespace.common');
NewNamespace.common = {
__name__: "NewNamespace.common",
__version__: "1.0",
myFunctionOne: function() {
// code
},
myFunctionTwo: function() {
// code
}
})(jQuery);
This is also an implementation of the Module Pattern, from Douglas Crockford (or is it more from Dustin Diaz?) as explained by Eric Miraglia, from YUI. I believe this comes from Crockford, due to his prior work on this area, but the discussion on Diaz’ blog is really full of useful information.
After showing this, some recommendations:
- Use UPPERCASE for your MainNamespace (making it MAINNAMESPACE) as this is more visible and make it clear that you are using a module
- Use a name that is under your control: your company name, for example. This will prevent namespace clashes with other code
- Make your code generic enough so that you can reuse it as many times as needed
I hope this helps with a better coding practice as well as to spread the word on namespaces 🙂