一般的实现好像都是用类的方式做的,换成闭包的方式是不是因为现在大多数新的框架都是通过 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);
}
}
登录后可查看更多问答,登录/注册