I figure if you are reading even this far you care / know about namespacing in JavaScript so I’m not going to go into WHY.
However, the HOW is here. But, okay, yeah, maybe some specific WHY.
We had been using a generic namespacing function that required plugging in the base name three times. Not really that much work, but kind of a pain if you want to redistribute it. So, it is now reworked to be changed only in one place. It requires three variables in the default global namespace but that ain’t bad, right?
var APPLICATION_NAMESPACE = "MYPROJECT";
var _global = this;
var _global[APPLICATION_NAMESPACE] = {};
_global[APPLICATION_NAMESPACE].namespace = function() {
var a=arguments, o=null, i, j, d;
for (i=0; i<a.length; i=i+1) {
d=a[i].split(".");
o=_global[APPLICATION_NAMESPACE];
for (j=(d[0] == APPLICATION_NAMESPACE) ? 1 : 0; j<d.length; j=j+1) {
o[d[j]]=o[d[j]] || {};
o=o[d[j]];
}
}
return o;
}So, _global here refers to window most of the time (but sometimes not so we need a reference to it). MYPROJECT can be whatever you want it to be.
When we use the namespacing stuff we refer to the specific namespace directly using JS dot-deliminated object syntax. This function goes soft on existing objects; it will not destroy a previously created object with the same name.
The function will ignore the name of the namespace if it is the first part in there. I’m not saying that well, but these calls are functionally identical and both namespace MYPROJECT.SomeOtherPart.
MYPROJECT.namespace("SomeOtherPart");
MYPROJECT.namespace("MYPROJECT.SomeOtherPart");
