Skip to content

Instantly share code, notes, and snippets.

@danshearmur
Last active December 30, 2015 03:29
Show Gist options
  • Save danshearmur/7769528 to your computer and use it in GitHub Desktop.
Save danshearmur/7769528 to your computer and use it in GitHub Desktop.
Simple dependency injection (requires ES5 support)
'use strict';
var inject;
var specify;
(function (root) {
var depList = {};
var things = {};
var toString = {}.toString;
function isString(thing) {
return toString.call(thing) === '[object String]';
}
function isUndefined(thing) {
return typeof(thing) === 'undefined' || thing === null;
}
function isFunction(thing) {
return toString.call(thing) === '[object Function]';
}
specify = function specify(name, deps /* optional */, thing) {
if (arguments.length === 2) {
thing = deps;
deps = [];
}
if (!isString(name) || !name.length) {
throw TypeError();
}
if (!Array.isArray(deps)) {
throw TypeError();
}
if (isUndefined(thing)) {
throw TypeError();
}
if (deps.length > 0 && !isFunction(thing)) {
throw TypeError();
}
depList[name] = deps;
return things[name] = thing;
};
inject = function inject(name /* optional */, deps, thing) {
if (arguments.length === 2) {
thing = deps;
deps = name;
name = false;
}
if (!Array.isArray(deps)) {
throw TypeError();
}
if (isUndefined(thing)) {
throw TypeError();
}
if (deps.length > 0 && !isFunction(thing)) {
throw TypeError();
}
if (name) {
specify(name, deps, thing);
}
var injectedDeps = deps.map(function (name) {
var dep = things[name];
if (isFunction(dep)) {
return inject(depList[name], dep);
}
return dep;
});
return thing.apply(root, injectedDeps);
};
}).call(this);
specify('singleton-example', {
x: 100,
y: 200,
name: 'example'
});
specify('service-example', ['singleton-example'], function (singleton) {
var store = {};
return {
set: function (name, str) {
store[name] = str;
},
get: function (name) {
return 'example ' + store[name];
}
}
});
inject('inject-example', ['service-example'], function (exmaple) {
example.set('test', 'test');
console.log(example.get('test')); // 'example test'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment