依賴收集

爲什麼要依賴收集

先看下面這段代碼

new Vue({
    template: 
        `<div>
            <span>text1:</span> {{text1}}
            <span>text2:</span> {{text2}}
        <div>`,
    data: {
        text1: 'text1',
        text2: 'text2',
        text3: 'text3'
    }
});

按照之前《響應式原理》中的方法進行綁定則會出現一個問題——text3在實際模板中並沒有被用到,然而當text3的數據被修改的時候(this.text3 = 'test')的時候,同樣會觸發text3的setter導致重新執行渲染,這顯然不正確。

先說說Dep

當對data上的對象進行修改值的時候會觸發它的setter,那麼取值的時候自然就會觸發getter事件,所以我們只要在最開始進行一次render,那麼所有被渲染所依賴的data中的數據就會被getter收集到Dep的subs中去。在對data中的數據進行修改的時候setter只會觸發Dep的subs的函數。

定義一個依賴收集類Dep。

class Dep {
    constructor () {
        this.subs = [];
    }

    addSub (sub: Watcher) {
        this.subs.push(sub)
    }

    removeSub (sub: Watcher) {
        remove(this.subs, sub)
    }
    /*Github:https://github.com/answershuto*/
    notify () {
        // stabilize the subscriber list first
        const subs = this.subs.slice()
        for (let i = 0, l = subs.length; i < l; i++) {
            subs[i].update()
        }
    }
}
function remove (arr, item) {
    if (arr.length) {
        const index = arr.indexOf(item)
        if (index > -1) {
            return arr.splice(index, 1)
    }
}

Watcher

訂閱者,當依賴收集的時候會addSub到sub中,在修改data中數據的時候會觸發dep對象的notify,通知所有Watcher對象去修改對應視圖。

class Watcher {
    constructor (vm, expOrFn, cb, options) {
        this.cb = cb;
        this.vm = vm;

        /*在這裏將觀察者本身賦值給全局的target,只有被target標記過的纔會進行依賴收集*/
        Dep.target = this;
        /*Github:https://github.com/answershuto*/
        /*觸發渲染操作進行依賴收集*/
        this.cb.call(this.vm);
    }

    update () {
        this.cb.call(this.vm);
    }
}

開始依賴收集

class Vue {
    constructor(options) {
        this._data = options.data;
        observer(this._data, options.render);
        let watcher = new Watcher(this, );
    }
}

function defineReactive (obj, key, val, cb) {
    /*在閉包內存儲一個Dep對象*/
    const dep = new Dep();

    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get: ()=>{
            if (Dep.target) {
                /*Watcher對象存在全局的Dep.target中*/
                dep.addSub(Dep.target);
            }
        },
        set:newVal=> {
            /*只有之前addSub中的函數纔會觸發*/
            dep.notify();
        }
    })
}

Dep.target = null;

將觀察者Watcher實例賦值給全局的Dep.target,然後觸發render操作只有被Dep.target標記過的纔會進行依賴收集。有Dep.target的對象會將Watcher的實例push到subs中,在對象被修改出發setter操作的時候dep會調用subs中的Watcher實例的update方法進行渲染。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章