-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvent_Emitter.js
More file actions
34 lines (31 loc) · 935 Bytes
/
Event_Emitter.js
File metadata and controls
34 lines (31 loc) · 935 Bytes
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
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'); // []
*/