Created
October 11, 2011 16:22
-
-
Save piotrkulpinski/1278576 to your computer and use it in GitHub Desktop.
Automating nested namespacing
This file contains 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
// 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