请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

老师,createStore 的实现中心思想是不是观察者模式?

一般的实现好像都是用类的方式做的,换成闭包的方式是不是因为现在大多数新的框架都是通过 createStore() 函数调用。

// 类方式
class createStore {
  constructor(initData = {}) {
    this.store = initData;
    this.observers = []; // 管理所有的订阅者,依赖
  }

  getStore() {
    return this.store;
  }

  update(value) {
    if (value !== this.store) {
      // 执行store的操作
      const oldValue = this.store
      // 将store更新
      this.store = value
      // 通知所有的订阅者,监听store的变化
      this.observers.forEach(async item => await item(this.store, oldValue))
    }
  }

  subscribe(fn) {
    this.observers.push(fn);
  }
}

正在回答 回答被采纳积分+3

1回答

yancy 2022-07-16 14:46:04

是的,本质上就是个观察者模式

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号