EventEmitter 实现
class EventEmitter {
constructor() {
this.events = {}
}
// 订阅事件
on(evt, callback, ctx) {
if (!this.events[evt]) {
this.events[evt] = []
}
this.events[evt].push(callback)
return this
}
// 发布事件
emit(evt, ...payload) {
const callbacks = this.events[evt]
if (callbacks) {
callbacks.forEach(cb => cb.call(this, payload));
}
return this
}
// 删除订阅
off(evt, callback) {
if (typeof evt === "undefined") {
delete this.events
} else if (typeof evt === "string") {
if (typeof callback === 'function') {
this.events[evt] = this.events[evt].filter((cb) => cb !== callback)
} else {
delete this.events[evt]
}
}
}
// 只触发一次的订阅
once(evt, callback, ctx) {
const proxyCallback = (...payload) => {
callback.apply(ctx, payload)
this.off(evt, proxyCallback)
}
this.on(evt, proxyCallback, ctx)
}
}
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
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