0
点赞
收藏
分享

微信扫一扫

JS手写实现发布订阅设计模式


大部分前端应该对设计模式了解都不多,但是对​​Vue​​​理解深刻的同学一定都知道发布订阅模式,因为​​Vue2​​​的响应式就是基于​​Object.defineProperty​​ + 发布订阅模式实现的。

今天我们就用JS简单实现一下发布订阅模式

// 观察者 watcher
class Dep {
constructor(callback) {
this.subs = [];
this.callback = callback;
}

addSub(sub) {
this.subs.push(sub);
}

notify() {
this.subs.forEach(item => item.update(this.callback));
}
}

// 订阅者 complier
class Sub {
constructor(val) {
this.val = val;
}

update(callback) {
this.val = callback(this.val);
}
}

// 发布者 observer
class Pub {
constructor() {
this.deps = [];
}

addDep(dep) {
this.deps.push(dep);
}

publish(dep) {
this.deps.forEach(item => item === dep && item.notify());
}
}

其实代码上难度不大,重点是设计的思路。

  • 微信公众号: Code程序人生
  • B站账号: LuckyRay123
  • 个人博客: http://rayblog.ltd/

欢迎关注我的各类账号, 持续更新优质前端内容



举报

相关推荐

0 条评论