Merrick Christensen - JavaScript Dependency Injection
var WelcomeController = function (Greeter) {
document.write(Greeter.greet());
};
var Injector = {
dependencies: {},
process: function(target) {
console.log('target:', target)
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var text = target.toString();
console.log('target.toString():',text)
var args = text.match(FN_ARGS)[1].split(',');
console.log('args:', args);
console.log('this.getDependencies(args):', this.getDependencies(args));
target.apply(target, this.getDependencies(args));
},
getDependencies: function(arr) {
console.log('fn: getDependencies', arr);
var self = this;
return arr.map(function(value) {
return self.dependencies[value];
});
},
register: function(name, dependency) {
this.dependencies[name] = dependency;
console.log('fn:register', this.dependencies)
}
};
var RobotGreeter = {
greet: function() {
return 'Domo Arigato';
}
};
var OtherGreeter = {
greet: function() {
return 'That will do pig.';
}
};
// Randomly register a different greeter to show that WelcomeController is truly dynamic.
Injector.register('Greeter', Math.random() > 0.5 ? RobotGreeter : OtherGreeter);
Injector.process(WelcomeController);