let state = {
msg: 'hello world !',
msg2: 'hello world2 !'
}
let action
// 行为收集(行为=控制+显示)
let watcher = (fn) => {
action = fn //记录,便于执行fn时存储
fn()
action = null //清空,避免执行行为时,再次收集
}
// 设置响应化
let reactiveFn = (state) => {
Object.keys(state).forEach(key => {
let value = state[key] //初始化
let fnArr = [];
Object.defineProperty(state, key, {
get() {
// 获取值时, 收集所有的行为
action && fnArr.push(action)
return value
},
set(newValue) {
// 设置值后, 执行所有的行为
value = newValue
fnArr.forEach(fn => fn())
}
})
})
}
reactiveFn(state)
watcher(() => {
app.innerHTML = state.msg
})
watcher(() => {
app2.innerHTML = state.msg + 'haha'
})
网友评论