Kruncher
ongelezen,4 mrt 2009, 14:50:2004-03-2009Log in om te reageren op de auteur
Log in om door te sturen
Je hebt geen rechten om berichten in deze groep te verwijderen
Oorspronkelijk bericht tonen
E-mailadressen zijn anoniem voor deze groep of je moet het recht 'E-mailadressen van leden bekijken' hebben om het oorspronkelijke bericht te kunnen bekijken.
aan 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