Kruncher
unread,Mar 4, 2009, 2:50:20 PM3/4/09Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Prototype: Core
Hi all,
A recent project of mine involved a lot of JavaScript, so naturally
there were a lot of namespaces. We found that we kept running into two
problems when using namespaces:
1. Sometimes a namespace was not available and would result in an
error:
First.Second.Third = { ... };
Resolving this issue caused some pretty ugly code:
if (!First)
First = {};
if (!First.Second)
First.Second = {};
if (!First.Second.Third)
First.Second.Third = {};
2. Sometimes we had scripts which were redefining the entire contents
of a namespace.
So, I came up with the method $namespace which aims to ease the above
two issues:
The following two examples of usage define/redefine values:
$namespace('First.Second').Third = {
foo: function() {
}
};
$namespace('First.Second.Third').foo2 = function() {
// Function could be located in another JS file/script...
};
The following examples show how to add to a namespace without
redefining the entire thing:
$namespace('First.Second.Third', {
foo: function() {
}
});
$namespace('First.Second.Third', {
foo2: function() {
// Function could be located in another JS file/script...
}
});
Here is the function implementation that I use:
var $global = window;
function $namespace(name, extension) {
var namespaces = name.split('.');
var parentNS = $global;
namespaces.each(function(nsID) {
var ns = parentNS[nsID];
if (ns === undefined || ns === null)
parentNS[nsID] = (ns = {});
parentNS = ns;
});
if (extension) // Extend namespace?
Object.extend(parentNS, extension);
return parentNS;
}
I thought that this could be of use to a lot of developers.
Let met know what you guys think!
Many thanks,
Lea Hayes