Skip to content

Instantly share code, notes, and snippets.

@piotrkulpinski
Created October 11, 2011 16:22
Show Gist options
  • Save piotrkulpinski/1278576 to your computer and use it in GitHub Desktop.
Save piotrkulpinski/1278576 to your computer and use it in GitHub Desktop.
Automating nested namespacing
// top-level namespace being assigned an object literal
var myApp = myApp || {};
// a convenience function for parsing string namespaces and
// automatically generating nested namespaces
function extend( ns, ns_string ) {
var parts = ns_string.split("."),
parent = ns,
i;
if ( parts[0] === "myApp" ) {
parts = parts.slice(1);
}
for ( i = 0; i < parts.length; i++ ) {
if ( typeof parent[parts[i]] == "undefined" ) {
//create a property if it doesnt exist
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
}
// extend myApp with a deeply nested namespace
var mod = extend(myApp, 'myApp.modules.module2');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment