-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (69 loc) · 1.82 KB
/
index.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
var tinyEE = function() {
if (!(this instanceof tinyEE))
return new tinyEE();
this.events = [];
};
tinyEE.prototype.addListener = function(id, cb, once) {
if (!id || !cb)
return console.error('tiny-ee: name and callback must not be null');
if ('function' !== typeof cb)
return console.error('tiny-ee: callback must be of type function');
this.events.push({
id : id,
cb : cb,
once : !!once
});
};
tinyEE.prototype.listeners = function(id) {
var ret = [];
for (var i = 0; i < this.events.length; ++i) {
if (this.events[i]
&& this.events[i].id === id)
ret.push({
id : this.events[i].id,
cb : this.events[i].cb
});
}
return ret;
};
tinyEE.prototype.removeListener = function(id, cb) {
for (var i = 0; i < this.events.length; ++i) {
if (this.events[i]
&& this.events[i].id === id
&& this.events[i].cb === cb)
this.events.splice(i--, 1);
}
};
tinyEE.prototype.removeAllListeners = function(id) {
for (var i = 0; i < this.events.length; ++i) {
if (this.events[i]
&& this.events[i].id === id)
this.events.splice(i--, 1);
}
};
tinyEE.prototype.on = function(id, cb) {
this.addListener(id, cb, false);
};
tinyEE.prototype.once = function(id, cb) {
this.addListener(id, cb, true);
};
tinyEE.prototype.emit = function() {
var self = this;
var args = arguments;
var id = args[0];
delete args['0'];
args = Object.keys(args).map(function(k) {return args[k]});
for (var i = 0; i < self.events.length; ++i) {
if (self.events[i]
&& self.events[i].id === id) {
(function (i) {
process.nextTick(function() {
self.events[i].cb.apply(null, args);
if (self.events[i].once)
self.events.splice(i--, 1);
});
})(i);
}
}
};
module.exports = tinyEE;