Last active
August 29, 2015 14:19
-
-
Save klipstein/58eb43b717ae5f211e2a to your computer and use it in GitHub Desktop.
Dependency injection idea
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
function createFactory() { | |
var args = [].slice.call(arguments); | |
var createFunc = args.pop(); | |
return function() { | |
if (arguments.length > 0) { | |
return createFunc.apply(null, arguments); | |
} else { | |
return createFunc.apply(null, args); | |
} | |
}; | |
} | |
var depA = {my: 'depA'}; | |
var depB = {my: 'depB'}; | |
var module = { | |
create: createFactory(depA, depB, function(depA, depB) { | |
return { | |
key: 'value', | |
depA: depA | |
}; | |
}) | |
}; | |
// in your code | |
var instanceWithoutDeps = module.create(); | |
// in test | |
var testDepA = {test: 'depA'}; | |
var testDepB = {test: 'depB'}; | |
var instanceWithDeps = module.create(testDepA, testDepB); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Idea came from delivering a module that contains all the default dependencies. Normally you have the dependencies outside and you have to care about collecting those in the default case, when you want to use it somewhere else. Maybe it is a good idea for the bootstrap/factory code, where you assemble your dependencies.
About the DOM problem: my assumption is that all dependencies are wrapped in a function so that a
require
-call would not hit the underlying service.