双向绑定的底层原理就是应用了发布订阅者模式结合数据劫持,通过Object.defineProperty()方法来劫持各个属性(需要数据绑定的属性,vue 双花括号里面的值就是需要双向数据绑定的属性,如name,
{{name}}
)的setter、getter,在数据发生变动时,就发布消息给订阅者,触发相应的监听回调,从而实现更新。详细可以自行查阅资料。下面是个人简单的理解。
双向数据绑定原理:1.Observer(劫持并监听多有属性,有变动通知订阅者) -》event.notify() -》2.Watcher(订阅者,更新视图) -》3.Compile(解析器)
1.Observer 递归 所有双向绑定的属性,使用Object.defindProperty()劫持get、set方法, get中Event.addSub() 添加订阅者,set中调用事件Event.notify发布消息。
function defineReactive(data, key, val) {
observe(val); // 递归遍历所有子属性
var event = new Eevnt();
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get: function() {
if (event.target) {
event.addSub(event.target); // 在这里添加一个订阅者
}
return val;
},
set: function(newVal) {
if (val === newVal) {
return;
}
val = newVal;
console.log('属性' + key + '已经被监听了,现在值为:“' + newVal.toString() + '”');
event.notify(); // 如果数据变化,通知所有订阅者
}
});
}
function observe(data) {
if (!data || typeof data !== 'object') {
return;
}
//
Object.keys(data).forEach(function(key) {
defineReactive(data, key, data[key]);
});
};
var library = {
book1: {
name: ''
},
book2: ''
};
observe(library);
library.book1.name = 'vue权威指南'; // 属性name已经被监听了,现在值为:“vue权威指南”
library.book2 = '没有此书籍'; // 属性book2已经被监听了,现在值为:“没有此书籍”
Event.js
// 事件管理中心
function Eevnt () {
this.subs = [];
}
Eevnt.prototype = {
target: this,
addSub: function(sub) {
this.subs.push(sub);
},
notify: function() {
this.subs.forEach(function(sub) {
sub.update();
});
}
};
3.Watcher
Watcher.js 中引入事件中心,指定target指向自己。
import Event from 'event.js';
function Watcher(vm, exp, cb) {
this.cb = cb;
this.vm = vm;
this.exp = exp;
this.value = this.get(); // 将自己添加到订阅器的操作
}
Watcher.prototype = {
update: function() {
this.run();
},
run: function() {
var value = this.vm.data[this.exp];
var oldVal = this.value;
if (value !== oldVal) {
this.value = value;
this.cb.call(this.vm, value, oldVal);
}
},
get: function() {
Event.target = this; // 缓存自己
var value = this.vm.data[this.exp] // 强制执行监听器里的get函数
Event.target = null; // 释放自己
return value;
}
};
html中使用 Watcher
<h1 id="name">{{name}}</h1>
var ele = document.querySelector('#name');
var selfVue = new SelfVue({
name: 'hello world'
}, ele, 'name');
window.setTimeout(function () {
console.log('name值改变了');
selfVue.data.name = 'canfoo';
}, 2000);
function SelfVue (data, el, exp) {
this.data = data;
observe(data);
el.innerHTML = this.data[exp]; // 初始化模板数据的值
new Watcher(this, exp, function (value) { // 使用Watcher就实现了绑定,给name属性添加了订阅和发布
el.innerHTML = value;
});
return this;
}
4.Compile
function compile (node) {
var nodeAttrs = node.attributes;
var self = this;
Array.prototype.forEach.call(nodeAttrs, function(attr) {
var attrName = attr.name;
if (self.isDirective(attrName)) {
var exp = attr.value;
var dir = attrName.substring(2);
if (self.isEventDirective(dir)) { // 事件指令
self.compileEvent(node, self.vm, exp, dir);
} else { // v-model 指令
self.compileModel(node, self.vm, exp, dir);
}
node.removeAttribute(attrName);
}
});
}