Last active
December 30, 2015 03:29
-
-
Save danshearmur/7769528 to your computer and use it in GitHub Desktop.
Simple dependency injection (requires ES5 support)
This file contains 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
'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); |
This file contains 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
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