Skip to content

Instantly share code, notes, and snippets.

@phawk
Created June 16, 2012 15:17
Show Gist options
  • Select an option

  • Save phawk/2941628 to your computer and use it in GitHub Desktop.

Select an option

Save phawk/2941628 to your computer and use it in GitHub Desktop.
JS Namespace function
// 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