-
Notifications
You must be signed in to change notification settings - Fork 7
/
event-emitter.ts
55 lines (40 loc) · 1.28 KB
/
event-emitter.ts
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
// * https://github.com/primus/eventemitter3
// * https://nodejs.org/api/events.html
// * ------------------------------------------------ EventEmitter simple
class EventEmitter {
private handlers: Record<string, Function[]> = {};
on(event: string, handler: Function) {
if (!this.handlers[event]) this.handlers[event] = [];
this.handlers[event].push(handler);
}
off(event: string, handler?: Function) {
if (!handler) {
this.handlers[event] = [];
} else {
this.handlers[event] = this.handlers[event].filter((fn) => fn !== handler);
}
if (!this.handlers[event]) delete this.handlers[event];
}
emit(event: string, data: any) {
if (!this.handlers[event]) return;
this.handlers[event].forEach((fn) => fn(data));
}
}
// * ------------------------------------------------ usage
{
const bus = new EventEmitter();
bus.on('radio', (e: number) => console.log('log1', e));
const handler = (e: number) => console.log('log2', e);
bus.on('radio', handler);
console.log('--------');
bus.emit('radio', 333);
bus.emit('useless', 333);
console.log('--------');
bus.off('radio', handler);
bus.emit('radio', 666);
console.log('--------');
bus.off('useless');
bus.off('radio');
bus.emit('radio', 999);
console.log('--------');
}