Skip to content

Instantly share code, notes, and snippets.

@marlun78
Last active August 29, 2015 13:57
Show Gist options
  • Save marlun78/9387247 to your computer and use it in GitHub Desktop.
Save marlun78/9387247 to your computer and use it in GitHub Desktop.
JavaScript dependency injection - sort of...
/**
* Dependency Injection
* Copyright (c) 2014, marlun78
* MIT License, https://gist.github.com/marlun78/bd0800cf5e8053ba9f83
*
* === EXAMPLE ===
* //Some module...
* (function () {
* var di = window.di;
*
* //Add some dependencies
* di.add('a', 'Hello');
* di.add('b', 'B');
* di.add('c', 'world');
* }());
*
*
* //Some other module...
* (function () {
* var di = window.di;
*
* //Inject and call later
* var injected = di.inject(log); //or di.inject(log, 'more args');
* injected(); //or injected('even more args');
*
* //Call directly
* di.call(log); //or di.call(log, 'more args');
*
* //Test function
* function log(a, x, c) {
* console.log([].slice.call(arguments));
* return [a, c].join(' ');
* }
* }());
*/
(function () {
'use strict';
var di = {},
registry = {},
arraySlice = Array.prototype.slice,
//Not so standardized in ES3/ES5 - might break ...
functionToString = Function.prototype.toString;
function injector(immediate, fn) {
var args, extras;
if (!isFunction(fn)) {
throw new TypeError;
}
args = parse(fn).map(resolve);
extras = arraySlice.call(arguments, 2);
return immediate ? fn.apply(fn, args.concat(extras)) : function injected() {
return fn.apply(fn, args.concat(extras, arraySlice.call(arguments)));
};
}
function add(key, value) {
registry[key] = value;
}
function resolve(key) {
return registry[key];
}
function parse(fn) {
var argsPattern = /\(([^\)]*)/,
separatorPattern = /\s*,\s*/,
match = functionToString.call(fn).match(argsPattern);
if (match && match.length > 1) {
return match[1].split(separatorPattern);
}
return [];
}
function isFunction(value) {
return typeof value === 'function';
}
di.add = add;
di.inject = injector.bind(this, false);
di.call = injector.bind(this, true);
this.di = di;
}.call(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment