-
Notifications
You must be signed in to change notification settings - Fork 3
/
eventEmiter.ts
52 lines (45 loc) · 1.12 KB
/
eventEmiter.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
interface fn {
(...payload: any): void;
}
class EventEmitter {
private events = new Map<string, fn[]>();
private on(eventName: string, callback) {
const event = this.events.get(eventName) || [];
event.push(callback);
this.events.set(eventName, event);
}
private emit(eventName: string, ...payload) {
const cbs = this.events.get(eventName);
cbs && cbs.forEach(cb => cb(...payload));
}
private off(eventName: string, callback: fn) {
let cbs = this.events.get(eventName);
if (cbs) {
cbs = cbs.filter(fn => fn !== callback);
this.events.set(eventName, cbs);
}
}
private once(eventName: string, callback: fn) {
const fn: fn = (...payload) => {
callback(...payload);
this.off(eventName, fn);
}
this.on(eventName, fn);
}
}
interface one {
name: string;
}
class One {
age: number = 1;
func1() {
console.log('one func1')
}
}
class Two implements One {
// constructor
age: number = 2;
func1() {
console.log('two func1')
}
}