Skip to content

Instantly share code, notes, and snippets.

@ZauberNerd
Created March 21, 2012 07:02
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 ZauberNerd/2145393 to your computer and use it in GitHub Desktop.
Save ZauberNerd/2145393 to your computer and use it in GitHub Desktop.
Completely decoupled IIFE (immediately-invoked function expressions) which are able to talk to each other without introducing any global variables.
(function (win, doc, undefined) {
var modules = Object.create(null),
moduleContext = {
sayHi: function () { console.log('HI from module'); }
},
handleRegisterModuleEvent = function handleRegisterModuleEvent(event) {
core.registerModule(event.module);
},
core = {
init: function () {
doc.addEventListener('registerModule', handleRegisterModuleEvent, false);
console.log('core initalized');
},
destroy: function () {
doc.removeEventListener('registerModule', handleRegisterModuleEvent, false);
console.log('core destroyed');
},
getContext: function () {
var context = Object.create(moduleContext);
context.additionalFoo = 'bar'; // just to demonstrate that the context could be modified before it get's returned
return Object.freeze(context);
},
registerModule: function (module) {
modules[module.name] = module(this.getContext());
console.log('module: ' + module.name + ' successfully registered.');
this.startModule(module.name); // in reality this call shouldn't be placed here, but to demonstrate the startup of a module i just wrote it to the registerModule method.
},
getModule: function (moduleName) {
return modules[moduleName];
},
startModule: function (moduleName) {
try {
console.log('starting module: ' + moduleName);
this.getModule(moduleName).start();
} catch (e) {
console.error("can't start module: " + moduleName + ' - ' + e);
}
},
stopModule: function (moduleName) {
try {
console.log('stopping module: ' + moduleName);
this.getModule(moduleName).stop();
} catch (e) {
console.error("can't stop module: " + moduleName + ' - ' + e);
}
}
};
core.init();
}(window, document));
(function (win, doc, undefined) {
var registerModule = doc.createEvent('Event');
registerModule.initEvent('registerModule', false, false);
registerModule.module = function myCoolModule(context) {
return {
start: function () {
console.log('myCoolModule started!');
this.speak();
console.log('context: ', context);
},
stop: function () {
console.log('myCoolModule stopped!');
},
doFoo: function (foo) { console.log('done: ' + foo); },
speak: function () {
context.sayHi();
}
};
};
doc.dispatchEvent(registerModule);
}(window, document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment