发布订阅
应用比较广泛的设计模式,发布订阅模式又叫观察者模式,它定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,
所有依赖于它的对象都将获得通知,(vue 源码中应用到发布订阅模式比较广泛,eventBus 也是一种发布订阅模式)
看下伪代码
class Event {
constructor() {
// 存储事件
this.callbacks = {};
}
// 监听
$on(name, fn) {
// 如果 存在那么直接push 否则创建一个空数组push
// (this.callbacks[name] || this.callbacks[name] = []).push(fn);
if(this.callbacks[name]){
this.callbacks[name].push(fn)
}else{
this.callbacks[name] = [fn]
}
}
}
// 触发事件
$emit(name, args) {
let cbs = this.callbacks[name];
// 如果存在循环遍历通知每一个订阅的事件的对象
if (cbs) {
cbs.forEach((item) => {
item.call(this,args);
});
}
}
// 取消
$off(name) {
this.callbacks[name] = null;
}
}
let event = new Event();
event.$on("event1", function (args) {
console.log("一个事件1", args);
});
event.$on("event1", function (args) {
console.log("另一个事件", args);
});
event.$on("event2", function (args) {
console.log("一个事件2", args);
});
event.$emit("event1", { name: "1" });
event.$emit("event2", { name: "22" });
event.$off("event1");
event.$emit("event1", { name: "1" });
vue 源码的 emit on 大致代码也是这样的











网友评论