发布订阅者模式
发布订阅模式其实是对象间的一对多的依赖关系(利用消息队列)
当一个对象的状态(state)发生改变时,所有依赖于它的对象都得到状态改变的通知
订阅者(Subscriber)把自自己想订阅的事件注册(Subscribe)到调度中心(Event Channel)
当发布者(Publisher)发布该事件(Publish Event)到调度中心,也就是该事件触发时,由调度中心统一调度(Fire Event)订阅者注册到调度中心的处理代码
例子
- 小王去书店买书
- 去书店,问,没有,回家
- 过一会 再去问,没有,回家
- …
- 发布订阅模式
- 去书店,问,没有,订阅($on)一个联系方式给店员
- 一旦有书,店员($emit)一个短信给小王
- 触发消息队列(message)去买书
手写发布订阅模式
/*
一个消息队列 {abc:[fn1,fn2,fn3]}
向消息队列中添加内容 $on
删除消息队列中的内容 $off
触发消息队列里面的内容 $emit
*/
class Observe {
constructor() {
this.message = {};
}
$on(type, fn) {
this.message[type]
? this.message[type].push(fn)
: (this.message[type] = [fn]);
}
$off(type, fn) {
if (!this.message[type]) return;
if (!fn) {
this.message[type] = undefined;
} else {
console.log("else");
this.message[type] = this.message[type].filter((el) => el != fn);
}
}
$emit(type) {
if (!this.message[type]) return;
this.message[type].forEach((el) => {
el();
});
}
}
const person1 = new Observe();
function handler1() {
console.log("handler1");
}
function handler2() {
console.log("handler2");
}
person1.$on("abc", handler1);
person1.$on("abc", handler2);
person1.$emit("abc");
console.log(person1);