Created
June 6, 2012 13:47
-
-
Save chambaz/2881948 to your computer and use it in GitHub Desktop.
RequireJS - Body Class Initiated Object Oriented AMD Module Pattern
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
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 | |
}); |
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
// 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