Event
2023-06-16 10:32:28
实现一个事件收发器 Event 类,继承自此类的对象拥有 on, off, once 和 trigger 方法
ts
// 满足下例使用示例:
const event = new Event();
function log(val) {console.log(val);};
event.on('foo_event', log);
event.trigger('foo_event', 'abc'); // 打印出 abc
event.off('foo_event', log);
event.trigger('foo_event', 'abc'); // 打印出 undefined
class Event {
constructor() {
this.events = {};
}
// 注册事件
on(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(callback);
}
// 关闭事件
off(eventName, callback) {
if (this.events[eventName]) {
if (callback) {
this.events[eventName] = this.events[eventName].filter(cb => cb !== callback);
} else {
delete this.events[eventName];
}
}
}
// 只执行一次事件
once(eventName, callback) {
const onceCallback = (...args) => {
callback(...args);
this.off(eventName, onceCallback);
};
this.on(eventName, onceCallback);
}
// 触发事件
trigger(eventName, ...args) {
const eventCallbacks = this.events[eventName];
if (eventCallbacks) {
eventCallbacks.forEach(callback => callback(...args));
}
}
}
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