下午写了两篇文章后也没什么事情,就看了会javascript框架设计的书,看到观察者模式,如下面代码:
下面用ts实现了一遍
type Func = (...args: any) => void;
class PubSub {
handlers: { [index: string]: Func[] };
constructor() {
this.handlers = {};
}
// 订阅事件
on(eventType: string, handler: Func) {
if (!(eventType in this.handlers)) {
this.handlers[eventType] = [];
}
this.handlers[eventType].push(handler);
return this;
}
// 触发事件
emit(eventType: string) {
// 获取触发到eventType事件的handler的参数
const handlerArgs = Array.prototype.slice.call(arguments, 1);
if (!(eventType in this.handlers)) {
console.warn(`eventType: ${eventType}不存在`);
return;
}
this.handlers[eventType].forEach((handler) => {
handler(...handlerArgs);
});
return this;
}
// 删除订阅事件
off(eventType: string, handler: Func) {
if (!(eventType in this.handlers)) {
console.warn(`eventType: ${eventType}不存在`);
return;
}
// 剔除handler
this.handlers[eventType] = this.handlers[eventType].filter(
(item) => item !== handler
);
return this;
}
}
突然想起来疫情期间在家里学习react的时候看的react的subscribe应该也是用的观察者模式,当时不知道这个,对这种可以很清晰优雅的更新状态的实现很惊讶,现在看来还是我太low了。
欢迎大家关注我的公众号