Skip to content

Instantly share code, notes, and snippets.

@wolthers
Created October 8, 2011 19:34
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 wolthers/1272756 to your computer and use it in GitHub Desktop.
Save wolthers/1272756 to your computer and use it in GitHub Desktop.
Automatic initialization of object literals
/*
Bootstrap
@author Michael Wolthers Nielsen - http://moredots.dk/
@description Bootstrap class for automatic initialization of object literals based on data-modules on the body tag.
@credits Based on ideas by Paul Irish, Blake Waters and David Desandro - http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/
@usage Bootstrap.init(ObjectLiteral);
Example body tag:
<body data-modules="{"ThumbnailList": ["destruct"], "MainMenu": ["doSomething"], "Lightboxes": ["showLogin"] }">
Will call:
ObjectLiteral.Common.init();
Objectliteral.ThumbnailList.init();
Objectliteral.ThumbnailList.destruct();
Objectliteral.MainMenu.init();
Objectliteral.MainMenu.doSomething();
Objectliteral.Lightboxes.init();
Objectliteral.Lightboxes.showLogin();
Objectliteral.Common.init() of the inited namespace will always be called (if it exists)
Objectliteral.{module}.init() will always be called (if it exists)
*/
var Bootstrap = (function($) {
var _namespace = {};
function init(ns) {
_namespace = ns;
var modules = $(document.body).data("modules"),
actions = [];
//Always init Common
exec( "Common", "init" );
for (var module in modules) {
actions = modules[module];
//Always execute init
exec(module, "init")
for (var i = 0, len = actions.length; i < len; i++) {
//Don't execute init twice
if(actions[i] !== "init") {
exec(module, actions[i] );
}
}
}
}
function exec( module, action ) {
if (action !== undefined && module !== "" && _namespace[module] && typeof( _namespace[module][action] ) == "function" ) {
_namespace[module][action]();
}
}
return {
init: init
}
}( jQuery ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment