依赖收集存储

每个key值都有一个数组,用来存储当前key的依赖,假设依赖是一个函数,保存在window。target上
function defineReactive(data,key,val) {
let dep = []
Object.defineProperty(data,key,{
enumerable:true,//可枚举
configurable:true,
get:()=>{
dep.push(window.target)
console.log(dep)
return val
},
set:(newVal)=>{
console.log(newVal,val)
if(val===newVal){
return
}
for (let i = 0;i<dep.length;i++){

dep[i](newVal,val)
}
val=newVal
}
})
}
将代码解耦封装成一个Dep类,专门管理依赖
export default class Dep {
constructor(){
this.subs = []
}
addSub(sub){
this.sub.push(sub)
}
removeSub(sub){
remove(this.subs,sub)
}
depend(){
if(window.target){
this.addSub(window.target)
}
}

notify(){
const subs = this.subs.slice()
for (let i = 0;l = subs.length;i<l;i++){

subs[i].undate()
}
}

}

function remove(arr,item) {
if(arr.length){
const index = arr.indexOf(item)
if(index>-1){
return arr.splice(index,1)
}
}
}


function defineReactive(data,key,val) {
let dep = new Dep()
Object.defineProperty(data,key,{
enumerable:true,//可枚举
configurable:true,
get:()=>{
dep.depend()
console.log(dep)
return val
},
set:(newVal)=>{
console.log(newVal,val)
if(val===newVal){
return
}
val=newVal
dep.notify()
}
})
}
posted @ 2020-03-25 21:28  码我滴码  阅读(220)  评论(0编辑  收藏  举报