vue.采用数据劫持结合发布者-订阅者模式的方式,通过Object.defineProperty()来劫持各个属性的setter和getter,数据变动时发布消息给订阅者,触发相应函数的回调。
要实现mvvm的双向绑定,需要实现如下几点:
流程图如下:
- function MVVM(options) {
- this.$options = options || {};
- var data = this._data = this.$options.data;
- var me = this;
- // 数据代理
- // 实现 vm.xxx -> vm._data.xxx
- Object.keys(data).forEach(function(key) {
- me._proxyData(key);
- });
- // 代理计算属性
- // 同样通过Object.defineProperty进行劫持
- this._initComputed();
- observe(data, this);
- this.$compile = new Compile(options.el || document.body, this)
- }
- MVVM.prototype = {
- $watch: function(key, cb, options) {
- new Watcher(this, key, cb);
- }
- }
MVVM入口文件,整合Observer/Compile/Watcher三者,达到数据变化->更新视图;视图变化->数据变更的双向绑定效果。(结合钩子函数,理解Vue生命周期中各个阶段的作用)
- function Observer(data) {
- Object.keys(data).forEach(function() {
- defineReactive(data, key, data[key]);
- });
- }
- function defineReactive(data, key, val) {
- var dep = new Dep();
- var childObj = observe(val);
- Object.defineProperty(data, key, {
- enumerable: true,
- // 可枚举
- configurable: false,
- // 不能再define
- get: function() {
- if (Dep.target) {
- dep.depend();
- }
- return val;
- },
- set: function(newVal) {
- if (newVal === val) {
- return;
- }
- val = newVal;
- // 新的值是object的话,进行监听
- childObj = observe(newVal);
- // 通知订阅者
- dep.notify();
- }
- });
- }
对需要监测的对象的每个属性进行递归遍历,通过Object.defineProperty设置setter和getter。当设置新的属性值时,触发相应的setter,通知订阅者。
- function Dep() {
- this.id = uid++;
- this.subs = [];
- }
- Dep.prototype = {
- addSub: function(sub) {
- this.subs.push(sub);
- },
- depend: function() {
- Dep.target.addDep(this);
- },
- notify: function() {
- this.subs.forEach(function(sub) {
- sub.update();
- });
- }
- };
订阅者模式,每个属性维护一个Dep,记录自己的订阅者(即watcher),notify通知每个订阅者执行相应的update方法,更新视图。
Compile做了两件事情:
解析流程如下:
- function compileElement(el) {
- var childNodes = el.childNodes,
- me = this; [].slice.call(childNodes).forEach(function(node) {
- var text = node.textContent;
- var reg = /\{\{(.*)\}\}/;
- // 解析元素节点
- if (me.isElementNode(node)) {
- me.compile(node);
- // {{}}替换变量
- } else if (me.isTextNode(node) && reg.test(text)) {
- me.compileText(node, RegExp.$1);
- }
- // 递归遍历子节点
- if (node.childNodes && node.childNodes.length) {
- me.compileElement(node);
- }
- });
- }
- compile: function(node) {
- var nodeAttrs = node.attributes,
- me = this; [].slice.call(nodeAttrs).forEach(function(attr) {
- // 指令以v-xxx命名
- // <span v-html="content"></span>
- var attrName = attr.name; // v-html
- if (me.isDirective(attrName)) {
- var exp = attr.value; // content
- var dir = attrName.substring(2);
- // 事件指令
- if (me.isEventDirective(dir)) {
- compileUtil.eventHandler(node, me.$vm, exp, dir);
- // 普通指令
- } else {
- compileUtil[dir] && compileUtil[dir](node, me.$vm, exp);
- }
- node.removeAttribute(attrName);
- }
- });
- }
- var compileUtil = {
- html: function(node, vm, exp) {
- this.bind(node, vm, exp, 'html');
- },
- bind: function(node, vm, exp, dir) {
- var updaterFn = updater[dir + 'Updater'];
- // 第一次初始化视图
- updaterFn && updaterFn(node, this._getVMVal(vm, exp));
- // 实例化Watcher,添加订阅者
- new Watcher(vm, exp,
- function(value, oldValue) {
- // 属性变化的视图更新函数
- updaterFn && updaterFn(node, value, oldValue);
- });
- },
- }
- var Updater = {
- htmlUpdater: function(node, value) {
- node.innerHTML = typeof value == 'undefined' ? '': value;
- }
- }
Watcher作为Observer与Compile之间通信的桥梁,属性变化的订阅者,做了如下的事情:
- function Watcher(vm, expOrFn, cb) {
- this.cb = cb;
- this.vm = vm;
- this.expOrFn = expOrFn;
- this.value = this.get();
- }
- Watcher.prototype = {
- update: function() {
- this.run();
- },
- run: function() {
- var value = this.get();
- var oldVal = this.value;
- if (value !== oldVal) {
- this.value = value;
- this.cb.call(this.vm, value, oldVal);
- }
- },
- get: function() {
- Dep.target = this;
- var value = this.getter.call(this.vm, this.vm);
- Dep.target = null;
- return value;
- }
- };
这里需要注意的点是,实例化watcher的时候,调用get方法,通过Dep.target = curInstance,强行触发获属性值的getter方法,在属性的订阅器中添加当前watcher实例。
双向绑定的原理很简单,通过数据劫持,当设置新属性值的时候通过订阅者更新视图;编译指令,替换变量,同时绑定更新函数到订阅者;对应事件绑定调用addEventListener进行监听。
参考文章
剖析Vue原理&实现双向绑定MVVM
来源: http://www.cnblogs.com/tangzhirong/p/7502769.html