Namespace
simple function to create a namespace based on a period delimited string
by JThomas
JavaScript
window.namespace = window.namespace || {
/*
** Parses a string of namespaces seperated by a period character
** and creates the logical namespacing and returns the top most
** namespace
*/
create: function(nsToCreate){
if(nsToCreate && typeof nsToCreate == 'string'){
var namespaces = nsToCreate.split('.'),
ns = window;
for(var i = 0, x; x = namespaces[i++];)
{
//Define a property (namespace) on the most current one and merge the existing or create an empty namespace
ns = ns[x] = (ns[x] || {});
}
return ns;
}
console.warn("namespace.create: Namespace string missing or invalid");
}
};
var index = namespace.create("myapp.settings.index");
index.name = "TopLevelNamespace";
console.log(index);