-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path2694-event-emitter.js
37 lines (33 loc) · 916 Bytes
/
2694-event-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
class EventEmitter {
constructor() {
this.events = {};
}
subscribe(event, cb) {
this.events[event] = this.events[event] ?? [];
this.events[event].push(cb);
return {
unsubscribe: () => {
this.events[event] = this.events[event].filter((f) => f !== cb);
//To avoid memory leaks adding a cleanup condition
if (this.events[event].length === 0) {
delete this.events[event];
}
},
};
}
emit(event, args = []) {
if (!(event in this.events)) return [];
return this.events[event].map((f) => f(...args));
}
}
/**
* const emitter = new EventEmitter();
*
* // Subscribe to the onClick event with onClickCallback
* function onClickCallback() { return 99 }
* const sub = emitter.subscribe('onClick', onClickCallback);
*
* emitter.emit('onClick'); // [99]
* sub.unsubscribe(); // undefined
* emitter.emit('onClick'); // []
*/