通過(guò) es6 Proxy 來(lái)實(shí)現(xiàn)一個(gè)數(shù)據(jù)響應(yīng)式
// obj 對(duì)象 setBind set方法 getLogger get方法
let onWatch = (obj, setBind, getLogger) => {
let handler = {
// target 是要攔截的目標(biāo)
get(target, property, receiver) {
getLogger(target, property)
// target 目標(biāo)對(duì)象 property 對(duì)應(yīng)屬性 receiver setter方法
return Reflect.get(target, property, receiver)
},
set(target, property, value, receiver) {
setBind(value, property)
// 相當(dāng)于 vue的 $set
return Reflect.set(target, property, value)
}
}
// obj 需要攔截的對(duì)象 handler 攔截行為
return new Proxy(obj, handler)
}
let obj = { a: 1 }
let p = onWatch(
obj,
(v, property) => {
console.log(`監(jiān)聽到屬性${property}改變?yōu)?{v}`)
},
(target, property) => {
console.log(`'${property}' = ${target[property]}`)
}
)
p.a = 2 // 輸出 監(jiān)聽到屬性a改變?yōu)?
p.a // 輸出 'a' = 2