-
Notifications
You must be signed in to change notification settings - Fork 0
/
28-EventEmitter.js
41 lines (38 loc) · 993 Bytes
/
28-EventEmitter.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
class EventEmitter {
constructor() {
this.events = {}
}
subscribe(event, cb) {
if (!this.events[event]) this.events[event] = []
let cbList = this.events[event]
cbList.push(cb)
this.events[event] = cbList
return {
unsubscribe: () => {
let arr = this.events[event]
let index = arr.indexOf(cb)
if (index !== -1) arr.splice(index, 1)
},
}
}
emit(event, args = []) {
if (!this.events[event]) return []
const listeners = this.events[event]
const result = []
for (const listener of listeners) {
result.push(listener(...args))
}
return result
}
}
/**
* const emitter = new EventEmitter();
*
* Subscribe to the onClick event with onClickCallback
* function onClickCallback() { return 99 }
* const sub = emitter.subscribe('onClick', onClickCallback);
*
* console.log(emitter.emit("onClick")); // [99]
* sub.unsubscribe(); // undefined
* console.log(emitter.emit("onClick")); // []
*/