$namespace enhancement idea

0 views
Skip to first unread message

Kruncher

unread,
Mar 4, 2009, 2:50:20 PM3/4/09
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

nlloyds

unread,
Mar 4, 2009, 6:12:25 PM3/4/09
to Prototype: Core
You should check out this library: http://code.google.com/p/namespacedotjs/

Thanks,

Nathan

Kruncher

unread,
Mar 10, 2009, 10:34:43 PM3/10/09
to Prototype: Core
Hi Nathan,

That's an interesting library that you have pointed out there; and
when I get some free time I am going to take a closer look at it.

Many thanks,
Lea Hayes

Radoslav Stankov

unread,
Mar 11, 2009, 2:12:12 PM3/11/09
to Prototype: Core
This little hack could be also useful:

String.prototype.namespace = function(objects, scope){
scope = scope || window;
this.split('.').each(function(name){
if (Object.isUndefined(scope[name])) scope[name] = {};
scope = scope[name];
});

if (objects) Object.extent(scope, objects);
return scope;
};

usage:

'com.mycompany.somepack'.namespace();
'site.pixeldepo.next.namespace({ someProperty: true });
'com.mycompany.somepack'.namespace({ someProproperty: true},
some.other.namespace);
Reply all
Reply to author
Forward
0 new messages