Created
August 29, 2018 10:01
-
-
Save sajanv88/56e0da2b445184abe1b3fe6d3fd12031 to your computer and use it in GitHub Desktop.
Simple Modern module pattern in JavaScript
This file contains hidden or 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
/** | |
* 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