bindr for dependency injection
by jcreamer898
HTML
<div id="car"></div>
JavaScript
(function() {
function Bindr() {
this.injections = {};
};
Bindr.prototype.bind = function(from, to) {
console.log(this);
this.injections[from] = to;
return this;
};
Bindr.prototype.run = function(obj) {
//console.log(obj, this);
for(var prop in obj) {
if(obj.hasOwnProperty(prop) && this.injections[prop]) {
obj[prop] = new this.injections[prop]();
}
}
};
var _binder = new Bindr();
window.bindr = function() {
if (arguments.length === 2) {
return _bindr.run.apply(this._bindr, arguments);
}
return this;
};
bindr.bind = _binder.bind;
})();
function Model() {
bindr(this, arguments);
};
function Car(make, model, color, service) {
this.make = make;
this.model = model;
this.color = color;
this.service = service;
bindr(this, arguments);
};
function Service() {};
function FakeService() {};
//Car.prototype = Object.create(Model);
bindr.bind('service', FakeService);
var ford = new Car('Ford', 'Fusion', 'Maroon');
document.getElementById('car').innerHTML = JSON.stringify(ford, null, 4);