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中的知识,^_^

posted @ 2018-04-19 23:29  怜白  阅读(4354)  评论(4编辑  收藏  举报