Skip to content

Instantly share code, notes, and snippets.

@rsturim
Created February 25, 2013 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsturim/5033687 to your computer and use it in GitHub Desktop.
Save rsturim/5033687 to your computer and use it in GitHub Desktop.
Automating nested namespacing. Credited to Addy Osmani, based on a pattern by Stoyan Stefanov. http://goo.gl/T8Vqk
// Convenience function for parsing string namespaces and
// automatically generating nested namespaces
function extendNamespace( ns, ns_string ) {
var parts = ns_string.split("."),
parent = ns,
pl;
pl = parts.length;
for ( var i = 0; i < pl; i++ ) {
// create a property if it doesn't exist
if ( typeof parent[parts[i]] === "undefined" ) {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
}
// usage
var MY_APP = MY_APP || {};
var singleLevelNestedNamepace = extendNamespace(MY_APP, "descendant1");
console.log(singleLevelNestedNamepace == MY_APP.descendant1); // outputs true
var doubleLevelNestedNamepace = extendNamespace(MY_APP, "descendant1.descendant2");
console.log(doubleLevelNestedNamepace == MY_APP.descendant1.descendant2); // outputs true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment