6-10 全局状态管理 - 全局store

// 闭包函数保存initData
export const createStore = (initData = {}) => (() => {
  let store = initData
  const observers = [] // 管理所有的订阅者,依赖

  // 获取store
  const getStore = () => store

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

  return {
    getStore,
    update,
    subscribe,
  }
})()

const store = createStore()

window.store = store
store.subscribe((newValue, oldValue) => {
  console.log(newValue, oldValue, '---')
})

版权声明:本文为bus_lupe原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。