class Dep{
constructor(){
this.subs = [];
}
addSub(sub){
this.subs.push(sub);
}
notify(){
this.subs.forEach(sub => {
sub.update();
})
}
}
Dep.target = null;
class Watch{
constructor(obj,key,cb){
Dep.target = this;
this.cb = cb;
this.obj = obj;
this.key = key;
this.val = obj[key];
Dep.target = null;
}
update(){
this.val = this.obj[this.key];
console.log(1111)
this.cb(this.val);
}
}
let data = {
name:'krysliang',
};
observe(data);
new Watch(data,'name',()=>{
console.log('监听到数据发生变化')
})
data.name = 'hhh';
function defineReactive(obj,key,val){
observe(val);//将属性值也监听一下
let dp = new Dep();
Object.defineProperty(obj,key,{
enumerable:true,
configurable:true,
get:function reactiveGetter(){
console.log('监听到有人获取数据拉');
if(Dep.target){
dp.addSub(Dep.target);
}
return val;
},
set:function reactiveSetter(newVal){
console.log('监听到有人设置数据拉')
val = newVal;
dp.notify();
}
})
}
function observe(obj){
if(!obj || typeof obj !=="object"){
return;//非对象不往下执行
}
Object.keys(obj).forEach(key => {
defineReactive(obj,key,obj[key]);
})
}
使用Object.defineProperty实现数据的绑定通知
最新推荐文章于 2023-07-10 09:21:14 发布