javascript实现双向数据绑定

时间:2023-03-08 21:11:39

双向数据绑定已经是面试中经常被问到的点,需要对原理和实现都要有一定了解。

  下面是实现双向绑定的两种方法:

    1. 属性劫持
    2. 脏数据检查

一、属性劫持

  主要是通过Object对象的defineProperty方法,重写data的set和get函数来实现的。

    在属性劫持中,主要通过 _observe(重定义get、set方法,实现数据变化更新视图)、_compile(实现视图初始化、并对元素绑定事件)、_updata(实现具体更新视图方法) 三个方法完成双向绑定。

  __observe方法中,_binding储存数据相关更新的watcher对象列表,set函数触发回更新所有相关的绑定视图对象:

 MyVue.prototype._observe = function (data) {
const _this = this
Object.keys(data).forEach(key => {
if (data.hasOwnProperty(key)) {
let value = data[key]
this._binding[key] = {
_directives: []
}
this._observe(value) Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get() {
return value
},
set(newValue) {
if (value !== newValue) {
value = newValue
_this._binding[key]._directives.forEach(item => {
item._updata()
})
}
}
})
}
})
}

  _compile方法中,会对DOM中的绑定命令进行解析,并绑定相关的处理函数:

 MyVue.prototype._compile = function (root) {
const _this = this
const nodes = root.children;
Object.values(nodes).forEach(nodeChild => {
if (nodeChild.children.length) {
this._compile(nodeChild)
} if (nodeChild.hasAttribute('v-click')) {
nodeChild.addEventListener('click', (function (params) {
const attrVal = nodeChild.getAttribute('v-click');
return _this.$methods[attrVal].bind(_this.$data)
})())
} if (nodeChild.hasAttribute('v-model') && (nodeChild.tagName = 'INPUT' || nodeChild.tagName == 'TEXTAREA')) {
nodeChild.addEventListener('input', (function (params) {
var attrVal = nodeChild.getAttribute('v-model');
_this._binding[attrVal]._directives.push(
new Watcher({
el: nodeChild,
vm: _this,
exp: attrVal,
attr: 'value'
})
) return function () {
_this.$data[attrVal] = nodeChild.value;
}
})())
} if (nodeChild.hasAttribute('v-bind')) {
const attrVal = nodeChild.getAttribute('v-bind');
_this._binding[attrVal]._directives.push(
new Watcher({
el: nodeChild,
vm: _this,
exp: attrVal,
attr: 'innerHTML'
})
)
}
})
}

  _updata函数,主要在_compile函数中调用进行视图初始化和set函数调用更新绑定数据的相关视图:

 function Watcher({ el, vm, exp, attr }) {
this.el = el
this.vm = vm
this.exp = exp
this.attr = attr this._updata()
} Watcher.prototype._updata = function () {
this.el[this.attr] = this.vm.$data[this.exp]
}

网上的一张属性劫持的运行图:

javascript实现双向数据绑定

  • Observer 数据监听器,能够对数据对象的所有属性进行监听,如有变动可拿到最新值并通知订阅者,内部采用Object.defineProperty的getter和setter来实现。
  • Compile 指令解析器,它的作用对每个元素节点的指令进行扫描和解析,根据指令模板替换数据,以及绑定相应的更新函数。
  • Watcher 订阅者, 作为连接 Observer 和 Compile 的桥梁,能够订阅并收到每个属性变动的通知,执行指令绑定的相应回调函数。
  • Dep 消息订阅器,内部维护了一个数组,用来收集订阅者(Watcher),数据变动触发notify 函数,再调用订阅者的 update 方法。

完整的代码请参考 Two Way Binding

二、脏数据检查

  主要通过执行一个检测来遍历所有的数据,对比你更改了地方,然后执行变化

    在脏检查中,作用域scope对象中会维护一个“watcher”数组,用来存放所以需要检测的表达式,以及对应的回调处理函数。

  对于所有需要检测的对象、属性,scope通过“watch”方法添加到“watcher”数组中: 

 Scope.prototype.watch = function(watchExp, callback) {
this.watchers.push({
watchExp: watchExp,
callback: callback || function() {}
});
}

  当Model对象发生变化的时候,调用“digest”方法进行脏检测,如果发现脏数据,就调用对应的回调函数进行界面的更新:

 Scope.prototype.digest = function() {
var dirty; do {
dirty = false; for(var i = 0; i < this.watchers.length; i++) {
var newVal = this.watchers[i].watchExp(),
oldVal = this.watchers[i].last; if(newVal !== oldVal) {
this.watchers[i].callback(newVal, oldVal);
dirty = true;
this.watchers[i].last = newVal;
}
}
} while(dirty); }

完整的代码请参考 Two Way Binding

如果喜欢请关注我的Github,给个Star吧,我会定期分享一些JS中的知识,^_^