Sandbox pattern
messing with the sandbox pattern
by Eric Hynds
JavaScript
// messing with the sandbox pattern v2
function AP(){
var args = Array.prototype.slice.call(arguments),
callback = args.pop(),
modules = (args[0] && typeof args[0] === "string") ? args : args[0],
i;
// make sure we call this as a constructor
if(!(this instanceof AP)){
return new AP(modules,callback);
}
// add modules to "this"
modules = [];
for(i in AP.modules){
if(AP.modules.hasOwnProperty(i)){
modules.push(AP.modules[i]);
}
}
// fire callback
callback.apply(this, modules);
}
AP.prototype = {
version: 1
};
// add some modules
AP.modules = {
vessels: {
init: function( instance ){
console.log("initing vessels", this, instance);
}
},
members: {
init: function( instance ){
console.log("initing members", this, instance);
}
}
};
// each module defined is passed in as arguments,
// so you can init them manually/use whatever method
// from the module you need.
AP(['members','vessels'], function(members, vessels){
// "this" is the AP instance
console.log("inside callback", this);
members.init(this);
vessels.init(this);
});