雙向綁定

Angular1.x是臟值檢測(cè)來處理

React或者Vue2,最新的Angular:通過數(shù)據(jù)劫持+發(fā)布訂閱模式
vue2.x重點(diǎn)是Object.defineProperty

通過Object.defineProperty的get和set進(jìn)行數(shù)據(jù)劫持
通過遍歷data數(shù)據(jù)進(jìn)行數(shù)據(jù)代理到this上
通過{{}}對(duì)數(shù)據(jù)進(jìn)行編譯
通過發(fā)布訂閱模式實(shí)現(xiàn)數(shù)據(jù)與視圖同步

數(shù)據(jù)劫持:

觀察對(duì)象,給對(duì)象增加Object.defineProperty
vue特點(diǎn)是不能新增不存在的屬性 不存在的屬性沒有g(shù)et和set
深度響應(yīng) 因?yàn)槊看钨x予一個(gè)新對(duì)象時(shí)會(huì)給這個(gè)新對(duì)象增加defineProperty(數(shù)據(jù)劫持)
// 創(chuàng)建一個(gè)Observe構(gòu)造函數(shù)
// 寫數(shù)據(jù)劫持的主要邏輯
function Observe(data) {
    // 所謂數(shù)據(jù)劫持就是給對(duì)象增加get,set
    // 先遍歷一遍對(duì)象再說
    for (let key in data) {     // 把data屬性通過defineProperty的方式定義屬性
        let val = data[key];
        observe(val);   // 遞歸繼續(xù)向下找,實(shí)現(xiàn)深度的數(shù)據(jù)劫持
      //被標(biāo)記的地方就是通過遞歸observe(val)進(jìn)行數(shù)據(jù)劫持添加上了get和set!!,遞歸繼續(xù)向a里面的對(duì)象去定義屬性
        Object.defineProperty(data, key, {
            configurable: true,
            get() {
                return val;
            },
            set(newVal) {   // 更改值的時(shí)候
                if (val === newVal) {   // 設(shè)置的值和以前值一樣就不理它
                    return;
                }
                val = newVal;   // 如果以后再獲取值(get)的時(shí)候,將剛才設(shè)置的值再返回去
                observe(newVal);    // 當(dāng)設(shè)置為新值后,也需要把新值再去定義成屬性,加上get,set!!!
            }
        });
    }
}

// 外面再寫一個(gè)函數(shù)
// 不用每次調(diào)用都寫個(gè)new
// 也方便遞歸調(diào)用
function observe(data) {
    // 如果不是對(duì)象的話就直接return掉
    // 防止遞歸溢出
    if (!data || typeof data !== 'object') return;
    return new Observe(data);
}

數(shù)據(jù)代理:
讓我們每次拿data里的數(shù)據(jù)時(shí),不用每次都寫一長(zhǎng)串,如mvvm._data.a.b這種,可以直接寫成mvvm.a.b這種顯而易見的方式

function Mvvm(options = {}) {  
    // 數(shù)據(jù)劫持
    observe(data);
    // this 代理了this._data
+   for (let key in data) {
        Object.defineProperty(this, key, {
            configurable: true,
            get() {
                return this._data[key];     // 如this.a = {b: 1}
            },
            set(newVal) {
                this._data[key] = newVal;
            }
        });
+   }
}

// 此時(shí)就可以簡(jiǎn)化寫法了
console.log(mvvm.a.b);   // 1
mvvm.a.b = 'ok';    
console.log(mvvm.a.b);  // 'ok'

數(shù)據(jù)編譯:把{{}}里面的內(nèi)容解析出來

function Mvvm(options = {}) {
    // observe(data);
        
    // 編譯    
+   new Compile(options.el, this);    
}

// 創(chuàng)建Compile構(gòu)造函數(shù)
function Compile(el, vm) {
    // 將el掛載到實(shí)例上方便調(diào)用
    vm.$el = document.querySelector(el);
    // 在el范圍里將內(nèi)容都拿到,當(dāng)然不能一個(gè)一個(gè)的拿
    // 可以選擇移到內(nèi)存中去然后放入文檔碎片中,節(jié)省開銷
    let fragment = document.createDocumentFragment();
    
    while (child = vm.$el.firstChild) {
        fragment.appendChild(child);    // 此時(shí)將el中的內(nèi)容放入內(nèi)存中
    }
    // 對(duì)el里面的內(nèi)容進(jìn)行替換
    function replace(frag) {
        Array.from(frag.childNodes).forEach(node => {
            let txt = node.textContent;
            let reg = /\{\{(.*?)\}\}/g;   // 正則匹配{{}}

            if (node.nodeType === 3 && reg.test(txt)) {
            function replaceTxt() {
                node.textContent = txt.replace(reg, (matched, placeholder) => {   
                    console.log(placeholder);   // 匹配到的分組 如:song, album.name, singer...
                    new Watcher(vm, placeholder, replaceTxt);   // 監(jiān)聽變化,進(jìn)行匹配替換內(nèi)容
                    //reduce 為數(shù)組中的每一個(gè)元素依次執(zhí)行回調(diào)函數(shù)
                    return placeholder.split('.').reduce((val, key) => {
                        return val[key]; 
                    }, vm);
                });
            };
            // 替換
            replaceTxt();
        }
    }
    
    replace(fragment);  // 替換內(nèi)容
    
    vm.$el.appendChild(fragment);   // 再將文檔碎片放入el中
}

發(fā)布訂閱:讓手動(dòng)修改后的數(shù)據(jù)改變后頁面也能改變。
發(fā)布訂閱主要靠的就是數(shù)組關(guān)系,訂閱就是放入函數(shù),發(fā)布就是讓數(shù)組里的函數(shù)執(zhí)行

// 發(fā)布訂閱模式  訂閱和發(fā)布 如[fn1, fn2, fn3]
function Dep() {
    // 一個(gè)數(shù)組(存放函數(shù)的事件池)
    this.subs = [];
}
Dep.prototype = {
    addSub(sub) {   
        this.subs.push(sub);    
    },
    notify() {
        // 綁定的方法,都有一個(gè)update方法
        this.subs.forEach(sub => sub.update());
    }
};
// 監(jiān)聽函數(shù)
// 通過Watcher這個(gè)類創(chuàng)建的實(shí)例,都擁有update方法
function Watcher(fn) {
    this.fn = fn;   // 將fn放到實(shí)例上
}
Watcher.prototype.update = function() {
    this.fn();  
};

let watcher = new Watcher(() => console.log(111));  // 
let dep = new Dep();
dep.addSub(watcher);    // 將watcher放到數(shù)組中,watcher自帶update方法, => [watcher]
dep.addSub(watcher);
dep.notify();   //  111, 111

數(shù)據(jù)更新視圖:
現(xiàn)在我們要訂閱一個(gè)事件,當(dāng)數(shù)據(jù)改變需要重新刷新視圖,這就需要在 replace替換的邏輯里來處理
通過new Watcher把數(shù)據(jù)訂閱一下,數(shù)據(jù)一變就執(zhí)行改變內(nèi)容的操作

function replace(frag) {
    // 省略...
    // 替換的邏輯
    node.textContent = txt.replace(reg, val).trim();
    // 監(jiān)聽變化
    // 給Watcher再添加兩個(gè)參數(shù),用來取新的值(newVal)給回調(diào)函數(shù)傳參
+   new Watcher(vm, RegExp.$1, newVal => {
        node.textContent = txt.replace(reg, newVal).trim();    
+   });
}

// 重寫Watcher構(gòu)造函數(shù)
function Watcher(vm, exp, fn) {
    this.fn = fn;
+   this.vm = vm;
+   this.exp = exp;
    // 添加一個(gè)事件
    // 這里我們先定義一個(gè)屬性
+   Dep.target = this;
+   let arr = exp.split('.');
+   let val = vm;
+   arr.forEach(key => {    // 取值
+      val = val[key];     // 獲取到this.a.b,默認(rèn)就會(huì)調(diào)用get方法
+   });
+   Dep.target = null;
}

當(dāng)獲取值的時(shí)候就會(huì)自動(dòng)調(diào)用get方法,于是我們?nèi)フ乙幌?code>數(shù)據(jù)劫持那里的get方法

function Observe(data) {
+   let dep = new Dep();
    // 省略...
    Object.defineProperty(data, key, {
        get() {
+           Dep.target && dep.addSub(Dep.target);   // 將watcher添加到訂閱事件中 [watcher]
            return val;
        },
        set(newVal) {
            if (val === newVal) {
                return;
            }
            val = newVal;
            observe(newVal);
+           dep.notify();   // 讓所有watcher的update方法執(zhí)行即可
        }
    })
}

當(dāng)set修改值的時(shí)候執(zhí)行了dep.notify方法,這個(gè)方法是執(zhí)行watcherupdate方法,那么我們?cè)賹?duì)update進(jìn)行修改一下

Watcher.prototype.update = function() {
    // notify的時(shí)候值已經(jīng)更改了
    // 再通過vm, exp來獲取新的值
+   let arr = this.exp.split('.');
+   let val = this.vm;
+   arr.forEach(key => {    
+       val = val[key];   // 通過get獲取到新的值
+   });
    this.fn(val);   // 將每次拿到的新值去替換{{}}的內(nèi)容即可
};

雙向數(shù)據(jù)綁定:

    // html結(jié)構(gòu)
    <input v-model="c" type="text">
    
    // 數(shù)據(jù)部分
    data: {
        a: {
            b: 1
        },
        c: 2
    }
    
    function replace(frag) {
        // 省略...
+       if (node.nodeType === 1) {  // 元素節(jié)點(diǎn)
            let nodeAttr = node.attributes; // 獲取dom上的所有屬性,是個(gè)類數(shù)組
            Array.from(nodeAttr).forEach(attr => {
                let name = attr.name;   // v-model  type
                let exp = attr.value;   // c        text
                if (name.includes('v-')){
                    node.value = vm[exp];   // this.c 為 2
                }
                // 監(jiān)聽變化
                new Watcher(vm, exp, function(newVal) {
                    node.value = newVal;   // 當(dāng)watcher觸發(fā)時(shí)會(huì)自動(dòng)將內(nèi)容放進(jìn)輸入框中
                });
                
                node.addEventListener('input', e => {
                    let newVal = e.target.value;
                    // 相當(dāng)于給this.c賦了一個(gè)新值
                    // 而值的改變會(huì)調(diào)用set,set中又會(huì)調(diào)用notify,notify中調(diào)用watcher的update方法實(shí)現(xiàn)了更新
                    vm[exp] = newVal;   
                });
            });
+       }
        if (node.childNodes && node.childNodes.length) {
            replace(node);
        }
    }

參考:https://www.bilibili.com/video/BV1u4411W7ei?p=2&spm_id_from=pageDriver

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容