1. 程式人生 > 其它 >自己實現一個狀態管理工具store

自己實現一個狀態管理工具store

結合上一篇自己實現的事件匯流排,實現自己的狀態管理工具

const {LQEventBus} = require('./event-bus')

class LQstore {
  constructor(option) {
    // 利用事件匯流排來通知資料變化
    this.lqEventBus = new LQEventBus()
    // 儲存 state資料
    this.state = option.state
    // 儲存 action
    this.action = option.action
    // 對資料進行劫持
    const keys = Object.keys(this.state)
    keys.forEach(key => {
      let value = this.state[key]
      Object.defineProperty(this.state,key,{
        get:() => {
          return value
        },
        set:(newValue) => {
          value = newValue
          this.lqEventBus.emit(key+"")
        }
      })
    })
  };

  // 派發action
  dispatch(storeName,payload) {
    this.action[storeName](this.state,payload)
  }

  // 監聽資料變化
  onState(storeName,callBack,thisArg) {
    // 利用事件匯流排來蒐集依賴
    this.lqEventBus.on(storeName,callBack,thisArg)
    return this.state[storeName]
  }

  // 取消監聽
  offState(storeName,callBack) {
    this.lqEventBus.off(storeName,callBack)
  }
}

// 測試程式碼

const lqStore = new LQstore({
  state:{
    name:'liuqi',
    age:18
  },
  action:{
    changeName(state,payload) {
      state.name = payload
    }
  },
})


function bar() {
  console.log('name被改變了')
}

let storeName = lqStore.onState('name',bar)

console.log(storeName)

lqStore.dispatch('changeName','kobe')
let storeName2 = lqStore.onState('name',() => {
  console.log('name2被改變了')
})

console.log(lqStore.state.name)
console.log(storeName2)
lqStore.offState('name',bar)
lqStore.dispatch('changeName','jamse')
console.log(lqStore.state.name)