在我们日常开发中,我们无论是vue还是react都有订阅发布模式,因此,发布订阅也是前端的一个重要知识点,在面试的小伙伴可能遇到过这样的问题:请简单的实现一下发布订阅模式。下面就由我来带你们轻松拿捏
他主要包含3个核心,订阅者,发布者,消息中心
发布者(Pub)
发布主题消息,主要包含3个功能,添加主题,删除主题,更新主题
// 发布者
class Pub {
constructor () {
this.deps = []; // 发布的主题列表
}
// 添加主题
addDep (dep) {
this.deps.push(dep);
}
// 移除主题
removeDep (dep) {
let index = this.deps.indexOf(dep);
if (index !== -1) {
this.deps.splice(index, 1);
return true;
} else {
return false;
}
}
// 更新主题
publish (dep) {
this.deps.forEach(item => item == dep && item.notify());
}
}
订阅者(Sub)
订阅者就是去消息中心去订阅主题消息,功能就是执行回调
// 订阅者
class Sub {
constructor (val) {
this.val = val;
}
update (callback) {
this.val = callback(this.val); // 执行订阅主题的函数
console.log('更新之后:', this.val);
}
}
消息中心(Dep)
消息中心就是,订阅者和发布者的中间桥梁,用于接收发布者的主题,和通知订阅者发布
// 消息中心
class Dep {
constructor (callback) {
this.subs = []; // 主题的订阅者
this.callback = callback;
}
// 添加订阅者
addSub (sub) {
this.subs.push(sub);
return this;
}
// 主题更新通知---调用订阅者update,通知所有订阅者
notify () {
this.subs.forEach(item => item.update(this.callback));
}
}
测试
// 新建主题,给主题中加订阅者
let dep = new Dep(item => item * item);
dep.addSub(new Sub(1)).addSub(new Sub(2)).addSub(new Sub(3));
// 新建发布者
let pub = new Pub();
// 添加主题
pub.addDep(dep);
// 发布者发布,通知这个主题的所有订阅者更新
pub.publish(dep);
``