首页 > 其他 > 详细

依赖收集存储

时间:2020-03-25 21:52:34      阅读:85      评论:0      收藏:0      [点我收藏+]
每个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()
}
})
}

依赖收集存储

原文:https://www.cnblogs.com/lk1186578324/p/12570631.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!