function Observer(obj,key,value){
var dep = new Dep();
if(Object.prototype.toString.call(value) == "[object object]"){
Object.keys(value).forEach(function(key){
new Observer(value,key,value[key])
})
}
Object.defineProperty(obj,key,{
enumerable:true,
configurable:true,
get:function(){
if(Dep.target){
dep.addSub(Dep.target)
}
return value;
},
set:function(newVal){
value = newVal;
dep.notify();
}
})
}
function Watcher(fn){
this.update = function(){
Dep.target= this;
fn();
Dep.target = null;
}
this.update();
}
function Dep(){
this.sub = [];
this.addSub = function(watcher){
this.sub.push(watcher)
}
this.notify = function(){
this.sub.forEach(function(watcher){
watcher.update();
})
}
}
var obj = {
a: 1,
b: 2,
c: 3
}
Object.keys(obj).forEach(function(key){
new Observer(obj, key, obj[key])
});
new Watcher(function(){
document.querySelector("#test").innerHTML = obj.a;
})
上面代码是我看到别人写的双向绑定,但是有一点我不明白,为什么Dep下面的sub是数组,因为我觉得现在这段代码中每一个sub数组中都会存储相同的watcher对象,而且每一次都要将以前添加进去的watcher对象执行一遍,我觉得这不是不合理吗,不是应该只执行这一次添加进去的watcher就可以了吗
可能我理解有错误,请指出,谢谢