![数据双向绑定原理图](https://i-blog.csdnimg.cn/blog_migrate/b81af4be195bef4384c234d5a0d8c56c.png)
Observer类:
class Observer{
constructor(data){
this.observe(data)
}
observe(data){
if(data && typeof data == "object" ){
Object.keys(data).forEach(key=>{
this.defineReactive(data,key,data[key])
})
}
}
defineReactive(data,key,value){
this.observe(value);
let dep = new Dep()
Object.defineProperty(data,key,{
enumerable:true,
configurable:false,
get(){
console.log(key)
Dep.target && dep.addSub(Dep.target) && console.log(Dep.target)
return value
},
set:(newVal)=>{
this.observe(newVal)
if(value !== newVal){
value = newVal
}
dep.notify()
}
})
}
}
Dep类
class Dep{
constructor(){
this.subs = []
}
addSub(watcher){
this.subs.push(watcher)
}
notify(){
this.subs.forEach(w=>w.update())
}
}
Watcher类
class Watcher{
constructor(vm,expr,cb){
this.vm = vm
this.expr = expr
this.cb = cb
this.oldVal = this.getOldVal()
}
getOldVal(){
Dep.target = this
let oldVal = compileUtil.getval(this.expr,this.vm)
Dep.target = null
return oldVal
}
update(){
let newVal = compileUtil.getval(this.expr,this.vm)
if(newVal !== this.oldVal){
this.cb(newVal)
}
}
}