Created
February 25, 2013 21:55
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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