-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
47 lines (38 loc) · 971 Bytes
/
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
export default class Events {
constructor(listeners = {}) {
this.listeners = listeners;
}
hasListeners(event) {
return event in this.listeners;
}
on(event, cb) {
if (!(event in this.listeners)) {
this.listeners[event] = [];
}
if (!this.listeners[event].includes(cb)) {
this.listeners[event].push(cb);
}
return {
unsubscribe: () => this.off(event, cb),
};
}
off(event, cb) {
if (!this.hasListeners(event)) {
return;
}
this.listeners[event] = this.listeners[event].filter(
(subCb) => subCb !== cb,
);
}
removeAll(event) {
this.listeners[event] = [];
}
emit(event, ...args) {
if (!this.hasListeners(event)) {
return;
}
this.listeners[event].forEach(function (cb) {
cb.call(null, ...args);
});
}
}