Skip to content

Instantly share code, notes, and snippets.

@sajanv88
Created August 29, 2018 10:01
Show Gist options
  • Save sajanv88/56e0da2b445184abe1b3fe6d3fd12031 to your computer and use it in GitHub Desktop.
Save sajanv88/56e0da2b445184abe1b3fe6d3fd12031 to your computer and use it in GitHub Desktop.
Simple Modern module pattern in JavaScript
/**
* myModule is a mini framework allows you to create your own dependency modules.
*/
const myModule = (function () {
var modules = {};
function define(name, deps, impl) {
for(var i = 0; i<deps.length; i++) {
deps[i] = modules[deps[i]];
}
modules[name] = impl.apply(impl, deps);
}
function get(name) {
return modules[name];
}
return {
define: define,
get: get
}
})();
/**
usage of myModule example
**/
//defined logger module commonly and you can inject this module in your application and make use of it.
myModule.define('logger', [], function () {
function print(msg) {
console.log('printing: ', msg);
}
return {
print: print
}
});
/**
another modules in my application called bar.
**/
myModule.define('bar', ['logger'], function (logger) {
function saySomething() {
logger.print('I am awesome');
}
return {
saySomething: saySomething
}
});
const app = myModule.get('bar');
app.saySomething();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment