Skip to content

Instantly share code, notes, and snippets.

@alanshaw
Created August 19, 2015 15:35
Show Gist options
  • Save alanshaw/f1bf1309097d315df052 to your computer and use it in GitHub Desktop.
Save alanshaw/f1bf1309097d315df052 to your computer and use it in GitHub Desktop.
The most simple dependency injector
// mod.js
module.exports = function (dep1, dep2, rest) {
/* ... */
}
// main.js
var dj = require('dependency-jockey')()
var mod = require('./mod')
function Dep1 () {}
function Dep2 () {}
dj.register('dep1', new Dep1)
dj.register('dep2', new Dep2)
// or
dj.register({
dep1: new Dep1,
dep2: new Dep2
})
var rest = 123
mod = dj(mod) // jock the deps
mod(rest) // mod is called with dep1, dep2 and rest
// dj.js
module.exports = function () {
var deps = {}
function dj (fn, ctx) {
var depNames = fn.toString() // TODO: Reap arg names from fn
return function () {
var args = [].slice.call(arguments)
var depArgs = depNames.map(function (name) {
return deps[name]
})
return fn.apply(ctx, depArgs.concat(args))
}
}
dj.register = function (name, obj) {
if (obj) {
deps[name] = obj
} else {
Object.keys(name).forEach(function (name, obj) { deps[name] = obj })
}
return dj
}
return dj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment