Skip to content

Instantly share code, notes, and snippets.

@chambaz
Created June 6, 2012 13:47
Show Gist options
  • Save chambaz/2881948 to your computer and use it in GitHub Desktop.
Save chambaz/2881948 to your computer and use it in GitHub Desktop.
RequireJS - Body Class Initiated Object Oriented AMD Module Pattern
require(["jquery"], function($) {
// grab and instantiate page modules
if($('body').attr('data-js')) {
var htmlData = $('body').attr('data-js').split(" "), deps = [], params = [], i;
for(i = 0; i < htmlData.length; i++) {
// remove prefix
var module = ('modules/'+htmlData[i]).split(':');
// store deps
deps.push(module[0]);
// and params, if present
params.push((module.length > 1) ? module.splice(1) : false);
}
require(deps, function() {
for(var i = 0; i < arguments.length; i++) {
if(!arguments || typeof arguments[i] !== 'function') {
continue;
}
// if corresponding index of params array then pass to module
if(params[i]) {
arguments[i](params[i]);
} else {
arguments[i]();
}
}
});
}
// global code can go here
});
// define module with dependencies
define([], function() {
// define class
function ClassName() {
// reference to class
var _this = this;
// optional self invoking init method
this.init = function() {
}();
}
// return function instantiating the class
return function() {
return new ClassName();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment