js vue中依赖收集

依赖收集是 Vue.js 和 Mobx.js 核心的之一。本段代码实现调用多个new Queue().task()进行依赖收集,在调用start()的时候再触发依赖

//依赖
function Dep(){
    this.deps=[];
    this.target=null
}
Dep.prototype.getDeps=function(){
    if(!this.target) return
    this.deps.push(this.target)
}
Dep.prototype.notify=async function(){
    for(var index in this.deps){
        var item =this.deps[index]
        await item.fn(item.time,item.callback)
    }
}
var dep = new Dep()

//队列函数
function Queue(){
    this.time=''
}
Queue.prototype.task=function(time,callback){
    dep.target={
        time:time,
        fn:this.fn,
        callback:callback
    }
    dep.getDeps()//收集依赖
    dep.target=null
}
Queue.prototype.fn=function(time,callback){
    return new Promise((resolve)=>{
        setTimeout(()=>{
            resolve(time)
            callback()
        },time)
    })
}
Queue.prototype.start=function(){
    console.log('start')
    dep.notify()//触发依赖
}

var queue=new Queue()
queue.task(3000, () => {console.log(3000)})
queue.task(2000, () => {console.log(2000)})
queue.start()

你可能感兴趣的:(js vue中依赖收集)