Created
June 11, 2015 16:52
-
-
Save javierarilos/7b29c5f6ecfc1b0bfe92 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Dependency injection used in frameworks like Angular.js, Require.js, Inject.js | |
// There are 3 types of dependency injection : setter, constructor and interface injection. | |
// Needs: a container or injector which can provide dependencies we need. | |
// Reasons for DI: two main reason to favor dependency injection : | |
// * improve maintainability | |
// * make it easier to test | |
var Injector = {dependencies: {}, | |
add : function(qualifier, obj){ | |
this.dependencies[qualifier] = obj;}, | |
get : function(func){ | |
var obj = new func(); | |
func.apply(obj, this.resolveDependencies(func)); | |
return obj;}, | |
resolveDependencies : function(func) { | |
var args = this.getParameters(func); | |
var dependencies = []; | |
for ( var i = 0; i < args.length; i++ ) { | |
dependencies.push(this.dependencies[args[i]]);} | |
return dependencies;}, | |
getParameters : function(func) {//regex from require.js | |
var PARAMS_REGEX = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; | |
var params = func.toString().match(PARAMS_REGEX)[1].split(','); | |
return params;}}; | |
var FancyLogger = function(){ | |
this.log = function(log){console.log(Date().toString("dd/MM/yyyy HH:mm:ss fff") + " : "+ log);}; | |
}; | |
var ItemController = function(logger){ | |
this.logger = logger; | |
this.doSomething = function(item){this.logger.log("Item["+item.id+"] handled!");}; | |
}; | |
Injector.add("logger", new FancyLogger()); | |
var itemController = Injector.get(ItemController); | |
itemController.doSomething({id : 5}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment