自己实现一个状态管理工具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)

浙公网安备 33010602011771号