Created
June 16, 2012 15:17
-
-
Save phawk/2941628 to your computer and use it in GitHub Desktop.
JS Namespace function
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
| // Core namespace | |
| var app = app || {}; | |
| app.namespace = function(namespace) { | |
| var spaces = namespace.split('.'); | |
| var nspace = function(spaces, index, progress) { | |
| // Check the namespace exists | |
| if (typeof spaces[index] === "undefined") { return; } | |
| // Create the current namespace | |
| if (typeof progress === "undefined") { | |
| // We are starting at the root level (will always be app) | |
| progress = app; | |
| } else { | |
| // We are continuing on a namespace | |
| var newSpace = spaces[index]; | |
| progress[newSpace] = progress[newSpace] || {}; | |
| progress = progress[newSpace]; | |
| } | |
| // Go deeper down the chain | |
| nspace(spaces, index + 1, progress); | |
| }; | |
| // Start namespace creation | |
| nspace(spaces, 0); | |
| }; | |
| // | |
| // Usage | |
| // | |
| // Create namespaces off 'app' of unknown lengths e.g. | |
| // | |
| app.namespace("app.views.homepage"); | |
| app.views.homepage = {}; | |
| app.namespace("app.views.loginmenu.loggedOut.view"); | |
| app.views.loginmenu.loggedOut.view = {}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment