Another DI
Yes it's yet another attempt at a DI. This time you just ask it for what you want in each module. While at the same time if you need to make a 'new' thing of the class, you can do.
by Sam Fereday
JavaScript
var Injector = function () {};
Injector.prototype = {
version: "0.1",
deps: {},
singletons: [],
_getSingleton: function (name) {
for (var i = 0; i < this.singletons.length; i += 1) {
if (this.singletons[i].name === name) return this.singletons[i];
}
},
add: function (name, construct) {
this.deps[name] = construct;
},
literal: function (name, obj) {
obj.name = name;
obj.isLiteral = true;
this.singletons.push(obj);
},
get: function (name, args, requireSingleton) {
var constructor, singleton, object;
if (typeof args === "boolean") {
requireSingleton = args;
args = [];
}
if (!args) args = [];
singleton = this._getSingleton(name);
if (singleton && requireSingleton || singleton && singleton.isLiteral) return singleton;
constructor = this.deps[name];
if (!constructor) throw "Dependency rejected: Could not find '" + name + "' component.";
object = Object.create(constructor.prototype);
object.dependencyId = this.makeId();
constructor.apply(object, args);
if (requireSingleton) this.singletons.push(object);
return object;
},
makeId: function () {
return ("0000" + (Math.random() * Math.pow(36, 4) << 0).toString(36)).slice(-4);
},
viewResources: function () {
return {
dependencies: this.deps,
singletons: this.singletons
};
}
}
var di = new Injector();
// Some component that something needs somewhere
var Hammertime = function () {
this.hasWhatYouNeed = true;
};
Hammertime.prototype = {
iLikeBigButts: true,
myOtherBrothersCantDeny: function () {
return this.iLikeBigButts;
}
}
// Register dependency
di.add("Hammertime", Hammertime);
// The classes (with some sneaky inheritance)
var Parent = function () {
this.name = "Parent";
...