Objectives...
- Remove vars, objects etc from the global object.
- Remove possibility of collisions.
Firstly I implement the Yahoo namespace code (note for example purposes I am using ROOT as the root of my namespace)...
if (typeof ROOT == "undefined" || !ROOT) {
var ROOT = {};
}
ROOT.namespace = function () {
var a = arguments,
o = null,
i, j, d;
for (i = 0; i < a.length; i = i + 1) {
d = ("" + a[i]).split(".");
o = ROOT;
for (j = (d[0] == "ROOT") ? 1 : 0; j < d.length; j = j + 1) {
o[d[j]] = o[d[j]] || {};
o = o[d[j]];
}
}
return o;
}
Now I declare my 1st namespace...
ROOT.namespace("UI");
ROOT.UI = {
utc: 12345,
getUtc: function() {
return this.utc;
}
}
What I want to do here is to hold vars that I need for my UI (in this case the current time in UTC) so that they are not on the global object. I also want to provide some specific functionality. This should be available on every page without any sort of instanciation...
Now I want to have an object stored within my namespace structure. However, this object will need to be created multiple times. The objective here is to keep this inside my structure but allow it to be created as many times as I need. This is as follows:
ROOT.namespace("AirportFinder");
ROOT.AirportFinder = function(){
this.var1 = 99999;
this.Display = function() {
alert(this.var1);
}
}
And this is the sample code to instanciate the object...
var test1 = new ROOT.AirportFinder();
test1.Display();
Is this a good pattern?