-
Notifications
You must be signed in to change notification settings - Fork 0
/
emitter.js
72 lines (62 loc) · 2.24 KB
/
emitter.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
function Emitter () {
this.events = {};
}
Emitter.prototype.count = function count(e) {
if (e) return this.events[e].length;
else return Object.keys(this.events).length;
}
function addCallback(e, cb, once, events) {
let cbs;
if (events[e] !== undefined) cbs = events[e];
else cbs = [];
cbs.push({cb: cb, once: once});
if (events.e === undefined) Object.assign(events, {[e]: cbs});
cbs = null;
}
Emitter.prototype.on = function on(e, cb) {
if (e && cb) {
if(typeof cb == 'function') addCallback(e, cb, false, this.events);
else throw new TypeError(`You add a listener as a type of ${typeof cb}, the type should be a function`);
}
return this;
}
Emitter.prototype.once = function once(e, cb) {
if (e && cb) {
if(typeof cb == 'function') addCallback(e, cb, true, this.events);
}
return this;
}
Emitter.prototype.emit = function emit(e, ...payload) {
let cbs = this.events[e];
if (cbs) {
cbs.forEach(function (item) {
item.cb(...payload);
});
cbs.forEach(function (item, index, object) {
if (item.once) object.splice(index, 1);
});
} else throw new Error(`Listener of event "${e}" doesn't exist`);
}
Emitter.prototype.off = function off(e, cb) {
if (e && cb) {
if (this.events[e]) {
let cbs = [];
for (var j = 0; j < this.events[e].length; j++) {
if (cb !== this.events[e][j].cb) cbs.push(this.events[e][j]);
}
this.events[e] = cbs;
if (this.count(e) === 0) delete this.events[e];
cbs = null;
} else throw new Error(`Event "${e}" or listener doesn't exist, can't remove listener`);
}
return this;
}
Emitter.prototype.removeAll = function removeAll() {
if (this.count !== 0) this.events = {};
return this;
}
Emitter.prototype.addEventListener = Emitter.prototype.on;
Emitter.prototype.addOneTimeListener = Emitter.prototype.once;
Emitter.prototype.removeListener = Emitter.prototype.off;
Emitter.prototype.removeAllListeners = Emitter.prototype.removeAll;
module.exports = Emitter;