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

来源:6-11 全局状态管理 - 全局store(2)

TimoHo

2022-07-15

一般的实现好像都是用类的方式做的,换成闭包的方式是不是因为现在大多数新的框架都是通过 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);
  }
}
写回答

1回答

yancy

2022-07-16

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

0
0

从0打造微前端框架,实战汽车资讯平台

专为2~5年前端工程师打造的架构能力提升课

791 学习 · 204 问题

查看课程