如今的前端面试无论你用的什么框架,总会问你这个框架的双向绑定机制,有的甚至要求你现场实现一个双向绑定出来,那对于没有好好研究过这方面知识的同窗来讲,固然是很难的,接下来本文用160行代码带你实现一个极简的双向绑定机制。若是喜欢的话能够点波赞/关注,支持一下,但愿你们看完本文能够有所收获。html
本文是在面试题:你能写一个Vue的双向数据绑定吗?的基础上仔细研究+改动,并添加了详细注释,而成的。前端
我的博客了解一下:obkoro1.comnode
codepen:仿Vue极简双向绑定git
Github:仿Vue极简双向绑定github
这个API是实现双向绑定的核心,最主要的做用是重写数据的get
、set
方法。web
let obj = {
singer: "周杰伦"
};
let value = "青花瓷";
Object.defineProperty(obj, "music", {
// value: '七里香', // 设置属性的值 下面设置了get set函数 因此这里不能设置
configurable: false, // 是否能够删除属性 默认不能删除
// writable: true, // 是否能够修改对象 下面设置了get set函数 因此这里不能设置
enumerable: true, // music是否能够被枚举 默认是不能被枚举(遍历)
// ☆ get,set设置时不能设置writable和value,要一对一对设置,交叉设置/同时存在 就会报错
get() {
// 获取obj.music的时候就会调用get方法
// let value = "强行设置get的返回值"; // 打开注释 读取属性永远都是‘强行设置get的返回值’
return value;
},
set(val) {
// 将修改的值从新赋给song
value = val;
}
});
console.log(obj.music); // 青花瓷
delete obj.music; // configurable设为false 删除无效
console.log(obj.music); // 青花瓷
obj.music = "听妈妈的话";
console.log(obj.music); // 听妈妈的话
for (let key in obj) {
// 默认状况下经过defineProperty定义的属性是不能被枚举(遍历)的
// 须要设置enumerable为true才能够 不然只能拿到singer 属性
console.log(key); // singer, music
}
复制代码
对,这里有个demo。面试
defineProperty
设置的属性,默认不能删除,不能遍历,固然你能够经过设置更改他们。兼容性:IE 9,Firefox 4, Chorme 5,Opera 11.6,Safari 5.1segmentfault
更详细的能够看一下MDN并发
Object.defineProperty()
重写数据的get、set,值更新就在set中通知订阅者更新数据。这部分讲的很清楚,如今有点懵逼也不要紧,看完代码,本身copy下来玩一玩以后,回头再看实现思路,相信会有收获的。app
<div id="app">
<input type="text" v-model="name">
<h3 v-bind="name"></h3>
<input type="text" v-model="testData1">
<h3>{{ testData1 }}</h3>
<input type="text" v-model="testData2">
<h3>{{ testData2 }}</h3>
</div>
复制代码
看到这个模板,相信用过Vue的同窗都不会陌生。
采用类Vue方式来使用双向绑定:
window.onload = function () {
var app = new myVue({
el: '#app', // dom
data: { // 数据
testData1: '仿Vue',
testData2: '极简双向绑定',
name: 'OBKoro1'
}
})
}
复制代码
实际上这里是咱们实现思路中的第四步,用于整合数据监听器this._observer()
、指令解析器this._compile()
以及链接Observer和Compile的_watcherTpl的watch池。
function myVue(options = {}) { // 防止没传,设一个默认值
this.$options = options; // 配置挂载
this.$el = document.querySelector(options.el); // 获取dom
this._data = options.data; // 数据挂载
this._watcherTpl = {}; // watcher池
this._observer(this._data); // 传入数据,执行函数,重写数据的get set
this._compile(this.$el); // 传入dom,执行函数,编译模板 发布订阅
};
复制代码
这是实现思路中的第三步,由于下方数据监听器_observer()
须要用到Watcher函数,因此这里就先讲了。
像实现思路中所说的,这里起到了链接Observer和Compile的做用:
在模板编译_compile()阶段发布订阅
在赋值操做的时候,更新视图
// new Watcher() 为this._compile()发布订阅+ 在this._observer()中set(赋值)的时候更新视图
function Watcher(el, vm, val, attr) {
this.el = el; // 指令对应的DOM元素
this.vm = vm; // myVue实例
this.val = val; // 指令对应的值
this.attr = attr; // dom获取值,如value获取input的值 / innerHTML获取dom的值
this.update(); // 更新视图
}
Watcher.prototype.update = function () {
this.el[this.attr] = this.vm._data[this.val]; // 获取data的最新值 赋值给dom 更新视图
}
复制代码
没有看错,代码量就这么多,可能须要把整个代码链接起来,多看几遍才可以理解。
实现思路中的第一步,用Object.defineProperty()
遍历data重写全部属性的get set。
而后在给对象的某个属性赋值的时候,就会触发set。
在set中咱们能够监听到数据的变化,而后就能够触发watch更新视图。
myVue.prototype._observer = function (obj) {
var _this = this;
Object.keys(obj).forEach(key => { // 遍历数据
_this._watcherTpl[key] = { // 每一个数据的订阅池()
_directives: []
};
var value = obj[key]; // 获取属性值
var watcherTpl = _this._watcherTpl[key]; // 数据的订阅池
Object.defineProperty(_this._data, key, { // 双向绑定最重要的部分 重写数据的set get
configurable: true, // 能够删除
enumerable: true, // 能够遍历
get() {
console.log(`${key}获取值:${value}`);
return value; // 获取值的时候 直接返回
},
set(newVal) { // 改变值的时候 触发set
console.log(`${key}更新:${newVal}`);
if (value !== newVal) {
value = newVal;
watcherTpl._directives.forEach((item) => { // 遍历订阅池
item.update();
// 遍历全部订阅的地方(v-model+v-bind+{{}}) 触发this._compile()中发布的订阅Watcher 更新视图
});
}
}
})
});
}
复制代码
这里是实现思路中的第三步,让咱们来总结一下这里作了哪些事情:
首先是深度遍历dom树,遍历每一个节点以及子节点。
将模板中的变量替换成数据,初始化渲染页面视图。
把指令绑定的属性添加到对应的订阅池中
一旦数据有变更,收到通知,更新视图。
myVue.prototype._compile = function (el) {
var _this = this, nodes = el.children; // 获取app的dom
for (var i = 0, len = nodes.length; i < len; i++) { // 遍历dom节点
var node = nodes[i];
if (node.children.length) {
_this._compile(node); // 递归深度遍历 dom树
}
// 若是有v-model属性,而且元素是INPUT或者TEXTAREA,咱们监听它的input事件
if (node.hasAttribute('v-model') && (node.tagName = 'INPUT' || node.tagName == 'TEXTAREA')) {
node.addEventListener('input', (function (key) {
var attVal = node.getAttribute('v-model'); // 获取v-model绑定的值
_this._watcherTpl[attVal]._directives.push(new Watcher( // 将dom替换成属性的数据并发布订阅 在set的时候更新数据
node,
_this,
attVal,
'value'
));
return function () {
_this._data[attVal] = nodes[key].value; // input值改变的时候 将新值赋给数据 触发set=>set触发watch 更新视图
}
})(i));
}
if (node.hasAttribute('v-bind')) { // v-bind指令
var attrVal = node.getAttribute('v-bind'); // 绑定的data
_this._watcherTpl[attrVal]._directives.push(new Watcher( // 将dom替换成属性的数据并发布订阅 在set的时候更新数据
node,
_this,
attrVal,
'innerHTML'
))
}
var reg = /\{\{\s*([^}]+\S)\s*\}\}/g, txt = node.textContent; // 正则匹配{{}}
if (reg.test(txt)) {
node.textContent = txt.replace(reg, (matched, placeholder) => {
// matched匹配的文本节点包括{{}}, placeholder 是{{}}中间的属性名
var getName = _this._watcherTpl; // 全部绑定watch的数据
getName = getName[placeholder]; // 获取对应watch 数据的值
if (!getName._directives) { // 没有事件池 建立事件池
getName._directives = [];
}
getName._directives.push(new Watcher( // 将dom替换成属性的数据并发布订阅 在set的时候更新数据
node,
_this,
placeholder,
'innerHTML'
));
return placeholder.split('.').reduce((val, key) => {
return _this._data[key]; // 获取数据的值 触发get 返回当前值
}, _this.$el);
});
}
}
}
复制代码
codepen:仿Vue极简双向绑定
Github:仿Vue极简双向绑定
若是以为还不错的话,就给个Star⭐️鼓励一下我吧~
本文只是一个简单的实现双向绑定的方法,主要目的是帮助各位同窗理解mvvm框架的双向绑定机制,也并无很完善,这里仍是有不少缺陷,好比:没有实现数据的深度对数据进行get
、set
等。但愿看完本文,你们能有所收获。
我的blog and 掘金我的主页,如需转载,请放上原文连接并署名。码字不易,感谢支持!本人写文章本着交流记录的心态,写的很差之处,不撕逼,可是欢迎指点。
若是喜欢本文的话,欢迎关注个人订阅号,漫漫技术路,期待将来共同窗习成长。
以上2018.6.24