Skip to content

Instantly share code, notes, and snippets.

@michealbenedict
Created May 4, 2011 14:59
Show Gist options
  • Save michealbenedict/955361 to your computer and use it in GitHub Desktop.
Save michealbenedict/955361 to your computer and use it in GitHub Desktop.
Javascript module-submodule pattern
var Module = (function() {
var ModuleBase = function(params) {
this.params = params || {};
}
var submodules = {
"module1" : "SubModule"
};
for(var key in submodules) {
var modulename = submodules[key];
// Create methods for FabBase
// based on specified Sub Modules
// *** ARRGH *** CLOSURE .. Remember to have variables passed to closure when assigning something inside a loop
ModuleBase.prototype[key] = (function(modulename) {
var obj = '';
// I am binding a function which returns object of the submodule created on call
// Example : fabObj.admin()
return function(params) {
if(obj == "") {
if(typeof(this) != "object") {
obj = null;
return obj
};
obj = new ModuleBase[modulename](params,this);
if(typeof(obj["init"]) == "function") obj["init"]();
}
return obj;
};
}(modulename));
}
return ModuleBase;
})();
// SubModule.js
var Module = (function(Module) {
Module.SubModule = function(params,base) {
this.base = base;
this.params = params || {};
}
Module.SubModule.prototype.init = function() {
console.log("init");
};
Module.SubModule.prototype.m1 = function() {
console.log("m1");
};
Module.SubModule.prototype.m2 = function() {
console.log("m2");
};
return FabModule;
})(Module);
var obj = new Module();
// creates object of SubModule if not present
obj.module1().m1();
obj.module1().m2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment