-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemitter.js
73 lines (55 loc) · 1.19 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
73
export default class Emitter {
constructor() {
this._emitters = {};
this._subscribers = [];
}
extend(event) {
const emitter = new Emitter();
emitter.key = event;
return emitter;
}
then(fn) {
this._subscribers.push(fn);
return this;
}
on(...items) {
if (!items.length) {
return this;
}
const event = items.shift();
if (typeof event === 'function') {
return this.then(event);
}
if (!this._emitters[event]) {
this._emitters[event] = this.extend(event);
}
return this._emitters[event].on(...items);
}
off(...items) {
if (!items.length) {
this._emitters = {};
return this;
}
const event = items.shift();
if (typeof event === 'function') {
const index = this._subscribers.indexOf(event);
if (index > -1) {
this._subscribers.splice(index, 1);
}
return this;
}
if (!this._emitters[event]) {
this._emitters[event] = this.extend(event);
}
return this._emitters[event].off(...items);
}
async emit(...items) {
await Promise.all(this._subscribers.map(
subscriber => subscriber.apply(this, items)
));
const event = items.shift();
if (typeof event === 'string') {
await this.on(event).emit(...items);
}
}
}