被观察者对象
let object = { id: 1, name: 'tom', age: 20 }
存储所有观察者函数的集合
let set = new Set()
let observ = fn => set.add(fn)
observ(print)
observ(print1)
observ(print2)
observ(print3)
observ(print4)
observ(print5)
通过 proxy 劫持 object 对象的 set ,get 方法
function observable(target) {
return new Proxy(target, {
set(target, propKey, value) {
let result = Reflect.set(target, propKey, value)
// 当对象的属性propKey值发生变化即刻调用set集合中的函数
for (let item of set) {
item()
}
return result
},
get(target, propKey) {
return Reflect.get(target, propKey)
},
})
}
观察者
function print() {
document.getElementsByClassName('box')[0].innerHTML = object.id
}
function print1() {
document.getElementsByClassName('box1')[0].innerHTML = object.name
}
function print2() {
document.getElementsByClassName('box2')[0].innerHTML = object.age
}
function print3() {
document.getElementsByClassName('box3')[0].innerHTML = object.gender
}
function print4() {
document.getElementsByClassName('box4')[0].innerHTML = object.hobby
}
function print5() {
document.getElementsByClassName('box5')[0].innerHTML = JSON.stringify(object)
}
创建一个代理对象,对代理对象的属性进行赋值或修改
let proxy = observable(object)
proxy.name = 'tom2'
proxy.gender = '男'
proxy.hobby = ['打球', '游泳']
proxy.info = function () {
console.log(this)
}