-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer.js
executable file
·136 lines (100 loc) · 2.87 KB
/
container.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
'use strict';
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
var Dependency = require('./dependency');
var Consumer = require('./consumer');
function Container() {
this.resolved = {};
this.unResolved = {};
this.consumers = [];
}
function destroyAndDelete(obj, name) {
obj[name].destroy();
delete obj[name];
}
Container.prototype.destroy = function () {
var name;
while (this.consumers.length) {
this.consumers.pop().destroy();
}
this.consumers = null;
for (name in this.unResolved) {
destroyAndDelete(this.unResolved, name);
}
this.unResolved = null;
for (name in this.resolved) {
destroyAndDelete(this.resolved, name);
}
this.resolved = null;
};
Container.prototype.getParamNames = function (func) {
var fnName = func.toString().replace(STRIP_COMMENTS, ''),
result = fnName.slice(fnName.indexOf('(') + 1, fnName.indexOf(')')).match(ARGUMENT_NAMES);
if (result === null) {
result = [];
}
return result;
};
Container.prototype.register = function (name, resolver) {
var deps = [],
dep;
if (typeof resolver === 'function') {
if (resolver.length) {
deps = this.getParamNames(resolver);
}
}
dep = new Dependency(this, name, deps, resolver);
dep.resolve();
};
Container.prototype.get = function (depName) {
var resolve = this.resolved[depName];
if (resolve) {
return resolve.fire();
}
return null;
};
Container.prototype.resolve = function (consumer) {
if (typeof consumer === 'function') {
return null;
}
var deps,
action,
c;
if (typeof consumer !== 'object' || !(consumer instanceof Array)) {
deps = Array.prototype.slice.call(arguments);
} else {
deps = consumer;
}
action = deps.pop();
if (typeof action !== 'function') {
return this.get(consumer);
}
c = new Consumer(this, deps, action);
c.resolve();
};
Container.prototype.notifyResolved = function (dependable) {
var i, consumers, consumer;
delete this.unResolved[dependable.name];
this.resolved[dependable.name] = dependable;
for (i in this.unResolved) {
this.unResolved[i].resolve();
}
consumers = this.consumers;
this.consumers = [];
while (consumers.length) {
consumer = consumers.pop();
if (consumer.action) {
consumer.resolve();
}
}
};
Container.prototype.unRegister = function (depName) {
var resolve = this.resolved[depName];
if (resolve) {
destroyAndDelete(this.resolved, depName);
}
this.consumers.forEach(function (consumer) {
console.log(consumer);
});
};
module.exports = Container;