interface CacheProps {
[key: string]: Array<((data?: unknown) => void)>;
}Ï
class Observer {
private caches: CacheProps = {}
on(eventKey: string, fn: (data: unknown) => void) {
this.caches[eventKey] = this.caches[eventKey] || [];
this.caches[eventKey].push(fn);
}
emit(eventKey: string, data: unknown) {
if (this.caches[eventKey]) {
this.caches[eventKey].forEach((fn) => fn(data))
}
}
off(eventKey: string, fn: (data: unknown) => void) {
if (this.caches[eventKey]) {
this.caches[eventKey] = fn ? this.caches[eventKey].filter((i) => i !== fn) : []
}
}
}
代码如上:
理解
- 对于发布订阅事件要做的无非是把回调函数和触发key进行绑定。在合适的时机将回调函数 放入一个数组中。在合适的时机将数组中的回调函数依次执行。
- 优化改进:保持单例模式。全局唯一。对象是否可以用Map实现 增加查找速度。