javascript實現雙向數據綁定


雙向數據綁定已經是面試中經常被問到的點,需要對原理和實現都要有一定了解。

  下面是實現雙向綁定的兩種方法:

    1. 屬性劫持
    2. 臟數據檢查

 

一、屬性劫持

  主要是通過Object對象的defineProperty方法,重寫data的set和get函數來實現的。

    在屬性劫持中,主要通過 _observe(重定義get、set方法,實現數據變化更新視圖)、_compile(實現視圖初始化、並對元素綁定事件)、_updata(實現具體更新視圖方法) 三個方法完成雙向綁定。

  __observe方法中,_binding儲存數據相關更新的watcher對象列表,set函數觸發回更新所有相關的綁定視圖對象:

 1 MyVue.prototype._observe = function (data) {
 2     const _this = this
 3     Object.keys(data).forEach(key => {
 4         if (data.hasOwnProperty(key)) {
 5             let value = data[key]
 6             this._binding[key] = {
 7                 _directives: []
 8             }
 9             this._observe(value)
10 
11             Object.defineProperty(data, key, {
12                 enumerable: true,
13                 configurable: true,
14                 get() {
15                     return value
16                 },
17                 set(newValue) {
18                     if (value !== newValue) {
19                         value = newValue
20                         _this._binding[key]._directives.forEach(item => {
21                             item._updata()
22                         })
23                     }
24                 }
25             })
26         }
27     })
28 }

 

  _compile方法中,會對DOM中的綁定命令進行解析,並綁定相關的處理函數:

 1 MyVue.prototype._compile = function (root) {
 2     const _this = this
 3     const nodes = root.children;
 4     Object.values(nodes).forEach(nodeChild => {
 5         if (nodeChild.children.length) {
 6             this._compile(nodeChild)
 7         }
 8 
 9         if (nodeChild.hasAttribute('v-click')) {
10             nodeChild.addEventListener('click', (function (params) {
11                 const attrVal = nodeChild.getAttribute('v-click');
12                 return _this.$methods[attrVal].bind(_this.$data)
13             })())
14         }
15 
16         if (nodeChild.hasAttribute('v-model') && (nodeChild.tagName = 'INPUT' || nodeChild.tagName == 'TEXTAREA')) {
17             nodeChild.addEventListener('input', (function (params) {
18                 var attrVal = nodeChild.getAttribute('v-model');
19                 _this._binding[attrVal]._directives.push(
20                     new Watcher({
21                         el: nodeChild,
22                         vm: _this,
23                         exp: attrVal,
24                         attr: 'value'
25                     })
26                 )
27 
28                 return function () {
29                     _this.$data[attrVal] = nodeChild.value;
30                 }
31             })())
32         }
33 
34         if (nodeChild.hasAttribute('v-bind')) {
35             const attrVal = nodeChild.getAttribute('v-bind');
36             _this._binding[attrVal]._directives.push(
37                 new Watcher({
38                     el: nodeChild,
39                     vm: _this,
40                     exp: attrVal,
41                     attr: 'innerHTML'
42                 })
43             )
44         }
45     })
46 }

 

  _updata函數,主要在_compile函數中調用進行視圖初始化和set函數調用更新綁定數據的相關視圖:

 1 function Watcher({ el, vm, exp, attr }) {
 2     this.el = el
 3     this.vm = vm
 4     this.exp = exp
 5     this.attr = attr
 6 
 7     this._updata()
 8 }
 9 
10 Watcher.prototype._updata = function () {
11     this.el[this.attr] = this.vm.$data[this.exp]
12 }

 

 網上的一張屬性劫持的運行圖:

 屬性劫持 

  • Observer 數據監聽器,能夠對數據對象的所有屬性進行監聽,如有變動可拿到最新值並通知訂閱者,內部采用Object.defineProperty的getter和setter來實現。
  • Compile 指令解析器,它的作用對每個元素節點的指令進行掃描和解析,根據指令模板替換數據,以及綁定相應的更新函數。
  • Watcher 訂閱者, 作為連接 Observer 和 Compile 的橋梁,能夠訂閱並收到每個屬性變動的通知,執行指令綁定的相應回調函數。
  • Dep 消息訂閱器,內部維護了一個數組,用來收集訂閱者(Watcher),數據變動觸發notify 函數,再調用訂閱者的 update 方法。

完整的代碼請參考 Two Way Binding

二、臟數據檢查

  主要通過執行一個檢測來遍歷所有的數據,對比你更改了地方,然后執行變化

    在臟檢查中,作用域scope對象中會維護一個“watcher”數組,用來存放所以需要檢測的表達式,以及對應的回調處理函數。

  對於所有需要檢測的對象、屬性,scope通過“watch”方法添加到“watcher”數組中: 

1 Scope.prototype.watch = function(watchExp, callback) {
2     this.watchers.push({
3         watchExp: watchExp,
4         callback: callback || function() {}
5     });
6 }

  當Model對象發生變化的時候,調用“digest”方法進行臟檢測,如果發現臟數據,就調用對應的回調函數進行界面的更新:

 1 Scope.prototype.digest = function() {
 2     var dirty;
 3 
 4     do { 
 5         dirty = false;
 6 
 7         for(var i = 0; i < this.watchers.length; i++) {
 8             var newVal = this.watchers[i].watchExp(),
 9                 oldVal = this.watchers[i].last;
10 
11             if(newVal !== oldVal) {
12                 this.watchers[i].callback(newVal, oldVal);
13                 dirty = true;
14                 this.watchers[i].last = newVal;
15             }
16         }
17     } while(dirty);
18 
19 }

完整的代碼請參考 Two Way Binding

 

如果喜歡請關注我的Github,給個Star吧,我會定期分享一些JS中的知識,^_^


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM