阐述一下对MVVM的理解(5000)

415 阅读11分钟
  1. 观察者模式:主体维护观察者列表,状态发生变化:(subject)主题->通知观察者。发布者/订阅者:由中间层消息代理(或消息队列)的帮助下进行通信。
  2. 在发布者/订阅者模式中,组件与观察者模式完全分离。在观察者模式中,主题和观察者松散耦合。
  3. 观察者模式主要是以同步方式实现。发布/订阅模式主要以异步方式实现(使用消息队列)。
  4. 发布者/订阅者模式更像是一种跨应用程序模式。发布和订阅可以在两个不同的应用程序中。它们中的每一个都通过消息代理或消息队列进行通信。
简单观察者
//观察者
class Subject{//被观察者 被观察者中存在观察者
    constructor(name){
        this.name = name
        this.observers = [];//存放所有观察者
        this.state = "被观察者心情很好!"
    }
    //被观察者要提供一个接收观察者的方法
    attach(observer){//订阅
        this.observers.push(observer);//存放观察者
    }
    setState(newState){//发布
        this.state = newState;
        //attach和setState就是发布订阅
        //下面的作用是传入最新方法
        this.observers.forEach(o => o.update(newState));
    }
}
class Observer{//把观察者注册到观察者中
    constructor(name){
        this.name = name
    }
    update(newState){
        console.log(this.name,",观察到:",newState)
    }
}
let sub = new Subject("被观察者")
let o1 = new Observer("观察者1")
let o2 = new Observer("观察者2")
let o3 = new Observer("观察者3")
sub.attach(o1);
sub.attach(o2);
//不会通知o3,因为o3没有注册
sub.setState("被观察者心情不好");//这样需要setState的方法
//这时候观察应该提供一个方法,用来通知所有的观察者状态更新了update()
简单发布订阅
//发布订阅 promise redux
let fs = require('fs')
//发布 -> 中间代理 <- 订阅
//观察者模式 观察者和被观察者,如果被观察者数据改变,通知观察者
let fs = require('fs')

class Events{
    constructor(){
        this.callbacks = []
        this.result = []
    }
    on(callback){
        this.callbacks.push(callback)
    }
    emit(data){
        this.result.push(data)
        this.callbacks.forEach(c=>c(this.result))
    }
}
let e = new Events();
e.on((arr)=>{
    if(arr.length==1){
        console.log(arr)
    } 
})
e.on((arr)=>{
    if(arr.length==1){
        console.log(arr)
    } 
})
fs.readFile('./name.txt','utf8',function(err,data){
    e.emit(data);
});
fs.readFile('./age.txt','utf8',function(err,data){
    e.emit(data);
});

#####观察者模式

//创建游戏
class PlayGame{
    constructor(name,level){
        this.name = name;
        this.level = level;
        this.observers = [];
    }
    publish(money){//发布
        console.log(this.level + '段位,' + this.name + '寻求帮助')
        this.observers.forEach((item)=>{
            item(money)
        })
    }
    subscribe(target,fn){//订阅
        console.log(this.level + '段位,' + this.name + '订阅了' + target.name)
        target.observers.push(fn)
    } 
}
//创建游戏玩家
let play1 = new PlayGame('play1', '钻石')
let play2 = new PlayGame('play2', '黄金')
let play3 = new PlayGame('play3', '白银')
let play4 = new PlayGame('play4', '青铜')


play1.subscribe(play4, (money)=>{
    console.log('钻石play1表示:' + (money >= 500? '' : '暂时很忙,不能') + '给予帮助')
})
play2.subscribe(play4, (money)=>{
    console.log('黄金play2表示:' + (money > 200 && money < 500? '' : '暂时很忙,不能') + '给予帮助')
})
play3.subscribe(play4, function(money){
    console.log('白银play3表示:' + (money <= 200 && money>100? '' : '暂时很忙,不能') + '给予帮助')
})


play4.publish(500)

#####发布订阅模式

class Game{
    constructor(){
        this.topics={}
    }
    subscribe(topic, fn){
        if(!this.topics[topic]){
              this.topics[topic] = [];  
        }
        this.topics[topic].push(fn);
    }
    publish(topic, money){
        if(!this.topics[topic]) return;
        for(let fn of this.topics[topic]){
            fn(money)
        }
    }
}
let game = new Game()
//玩家
class Player{
    constructor(name,level){
        this.name = name;
        this.level = level;
    }
    publish(topic, money){//发布
        console.log(this.level + '猎人' + this.name + '发布了狩猎' + topic + '的任务')
	    game.publish(topic, money)
    }
    subscribe(topic, fn){//订阅
        console.log(this.level + '猎人' + this.name + '订阅了狩猎' + topic + '的任务')
	    game.subscribe(topic, fn)
    } 
}
//创建游戏玩家
let play1 = new Player('play1', '钻石')
let play2 = new Player('play2', '黄金')
let play3 = new Player('play3', '白银')
let play4 = new Player('play4', '青铜')

play1.subscribe('龙', (money) => {
    console.log('play1' + (money > 200 ? '' : '不') + '接取任务')
})
play2.subscribe('老虎', (money)=>{
    console.log('play2接取任务')
})
play3.subscribe('牛', (money)=>{
    console.log('play3接取任务')
})
play4.subscribe('羊', (money)=>{
    console.log('play4接取任务')
})
play4.publish('老虎',500)

js创建对象的两种方式

//第一种
var person = new Object();
person.name = "Nicholas";
person.age = 29;
person.job = "Software Engineer";
person.sayName = function(){
    alert(this.name);
}
//第二种
var person = {
    name: "Nicholas",
    age: 29,
    job: "Software Engineer",
    sayName: function() {
        alert(this.name);
    }
}

####属性描述符:

#####数据属性:数据属性包含一个数据值的位置,在这个位置可以读取和写入值

1、可配置性 [[Configurable]] : 表示能否通过delete删除属性,能否修改属性特性,能否把数据属性修改为访问器属性。
2、可枚举性[[Enumerable]]:表示能否通过for-in循环返回属性。
3、可写入性[[Writable]]:表示能否修改属性值。
4、属性值[[Value]]:表示属性值。

#####访问器属性:是包含一对getter和setter函数

1、可配置性 [[Configurable]]:表示能否通过delete删除属性,能否修改属性特性,能否把访问器属性修改为数据属性。
2、可枚举性[[Enumerable]]:表示能否通过for-in循环返回属性。
3、读取属性函数[[Get]]:在读取属性时调用的函数。
4、写入属性函数[[Set]]:在写入属性时调用的函数。
Object.defineProperty()方法对数据属性和访问器属性进行修改
该方法接受三个参数:属性所在对象,属性名字和一个描述符对象
Object.getOwnPropertyDescriptor()方法取得指定对象指定属性的描述符
这个方法接收两个参数:属性所在对象,属性名字

###如果要求对用户的输入进行特殊处理,或者设置属性的依赖关系,就需要用到访问器属性了

#####object.defineProperties

var book = {}; 
Object.defineProperties(book, { 
 _year: {
    writable:true,
    value: 2004 
 }, 
 edition: { 
    value: 1 
 }, 
 year: { 
     get: function(){
        return this._year; 
     }, 
     set: function(newValue){ 
        console.log("++++",newValue)
        if (newValue > 2004) { 
             this._year = newValue; 
             this.edition += newValue - 2004; 
        }
        
    } 
 } 
});
book._year
console.log(book.year)
book.year = 2007
console.log(book.year)

#####数据绑定小案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input id="input"/></br>
    <button id="btn">提交数据</button>
    <script>
        let inputNode = document.getElementById('input');
        let person = {}
        Object.defineProperty(person, 'name' ,{
            configurable: true,
            get: function () {
                console.log('访问器的GET方法:'+ inputNode.value)
                return inputNode.value
            },
            set: function (newValue) {
                console.log('访问器的SET方法:' + newValue)
                inputNode.value = newValue
            }
        })
        inputNode.oninput = function () {
            console.log('输入的值: ' + inputNode.value)
            person.name = inputNode.value;
        }
    
        let btn = document.getElementById('btn');
        btn.onclick = function () {
            alert(person.name)
        }
    </script>
</body>
</html>

####MVVM设计模式

#####Vue双向绑定的的原理

vue.js 是采用数据劫持结合发布者-订阅者模式的方式,通过Object.defineProperty()来劫持各个属性的setter

getter,在数据变动时发布消息给订阅者,触发相应的监听回调。

具体步骤:

第一步:需要oberver的数据对象进行递归遍历,包括子属性对象的属性,都加上setter和getter方法

这样做就可以监听到数据的变化。

第二步:compile解析模版指令,将模版中的变量替换成数据,然后初始化渲染页面视图,并将每个指令对应的节点绑定更新函数,添加监听数据的订阅者,一旦数据有变动,收到通知,更新视图。
第三步:Watcher订阅者时Observer和Compile之间通信的桥梁,主要做事情是:
  1. 在自身实例化时忘属性订阅器(dep)里面添加自己
  2. 自身必须有一个update()方法
  3. 待属性变动dep.notice()通知时,能调用自身的update()方法,并触发Compile中的绑定的回调函数
第四步:MVVM作为数据绑定的入口,整合Observer、Compile和Watcher三者,通过Observer来监听自己的model数据变化,通过Conpile来解析编译模版指令,最终利用Watcher搭起Observer和Compile之间的通信桥梁,达到数据变化->视图更新->视图交互变化(input)->数据model变更的双向绑定效果

第一步:

function observe(data) {
    if (!data || typeof data !== 'object') {
        return;
    }
    // 取出所有属性遍历
    Object.keys(data).forEach(function(key) {
        defineReactive(data, key, data[key]);
    });
};
function defineReactive(data, key, val){
    observe(val); // 监听子属性
    Object.defineProperty(data, key, {
        enumerable: true, // 可枚举
        configurable: false, // 不能再define
        get: function() {
            return val;
        },
        set: function(newVal) {
            console.log('监听数据变化:', val, ' --> ', newVal);
            val = newVal;
        }
    });
}
var data = {name: '原始数据'};
observe(data);
data.name = '改变数据';
如何通知订阅者,我们需要实现一个消息订阅器,很简单,维护一个数组,用来收集订阅者,数据变动触发notify,再调用订阅者的update方法,代码改善之后是这样
/*订阅器*/
//。。。省略
function defineReactive(data, key, val){
    var dep = new Dep();//创建订阅器
    observer(val);
    Object.defineProperty(data, key, {
        // 。。。省略
        set: function(newVal) {
            if(val===newVal) return;
            console.log('监听数据变化:', val, ' --> ', newVal);
            val = newVal;
            dep.notify(); // 通知所有订阅者
        }
    });
}
function Dep() {
    this.subs = [];
}
Dep.prototype = {
    addSub: function(sub) {
        this.subs.push(sub);
    },
    notify: function() {
        this.subs.forEach(function(sub) {
            sub.update();
        });
    }
};

######谁是订阅者?订阅者应该是Watcher, 而且var dep = new Dep();是在 defineReactive方法内部定义的,所以想通过dep添加订阅者,就必须要在闭包内操作,所以我们可以在 getter里面动手脚:

/*订阅者*/
// ...省略
Object.defineProperty(data, key, {
    get: function() {
        // 由于需要在闭包内添加watcher,所以通过Dep定义一个全局target属性,暂存watcher, 添加完移除
        Dep.target && dep.addDep(Dep.target);
        return val;
    }
    // ... 省略
});
// Watcher.js
Watcher.prototype = {
    get: function(key) {
        Dep.target = this;
        this.value = data[key];    // 这里会触发属性的getter,从而添加订阅者
        Dep.target = null;
    }
}
//这里已经实现了一个Observer了,已经具备了监听数据和数据变化通知订阅者的功能
完整代码
function Observer(data) {
    this.data = data;
    this.walk(data);
}

Observer.prototype = {
    constructor: Observer,
    walk: function(data) {
        var me = this;
        Object.keys(data).forEach(function(key) {
            me.convert(key, data[key]);
        });
    },
    convert: function(key, val) {
        this.defineReactive(this.data, key, val);
    },

    defineReactive: function(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();
            }
        });
    }
};

function observe(value, vm) {
    if (!value || typeof value !== 'object') {
        return;
    }

    return new Observer(value);
};


var uid = 0;

function Dep() {
    this.id = uid++;
    this.subs = [];
}

Dep.prototype = {
    addSub: function(sub) {
        this.subs.push(sub);
    },

    depend: function() {
        Dep.target.addDep(this);
    },

    removeSub: function(sub) {
        var index = this.subs.indexOf(sub);
        if (index != -1) {
            this.subs.splice(index, 1);
        }
    },

    notify: function() {
        this.subs.forEach(function(sub) {
            sub.update();
        });
    }
};

Dep.target = null;

实现Compile

######compile主要做的事情是解析模板指令,将模板中的变量替换成数据,然后初始化渲染页面视图,并将每个指令对应的节点绑定更新函数,添加监听数据的订阅者,一旦数据有变动,收到通知,更新视图:

######因为遍历解析的过程有多次操作dom节点,为提高性能和效率,会先将跟节点el转换成文档碎片fragment进行解析编译操作,解析完成,再将fragment添加回原来的真实dom节点中

function Compile(el) {
    this.$el = this.isElementNode(el) ? el : document.querySelector(el);
    if (this.$el) {
        this.$fragment = this.node2Fragment(this.$el);
        this.init();
        this.$el.appendChild(this.$fragment);
    }
}
Compile.prototype = {
    init: function() { this.compileElement(this.$fragment); },
    node2Fragment: function(el) {
        var fragment = document.createDocumentFragment(), child;
        // 将原生节点拷贝到fragment
        while (child = el.firstChild) {
            fragment.appendChild(child);
        }
        return fragment;
    }
};
compileElement方法将遍历所有节点及其子节点,进行扫描解析编译,调用对应的指令渲染函数进行数据渲染,并调用对应的指令更新函数进行绑定
Compile.prototype = {
    // ... 省略
    compileElement: function(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-text="content"></span> 中指令为 v-text
            var attrName = attr.name;    // v-text
            if (me.isDirective(attrName)) {
                var exp = attr.value; // content
                var dir = attrName.substring(2);    // text
                if (me.isEventDirective(dir)) {
                    // 事件指令, 如 v-on:click
                    compileUtil.eventHandler(node, me.$vm, exp, dir);
                } else {
                    // 普通指令
                    compileUtil[dir] && compileUtil[dir](node, me.$vm, exp);
                }
            }
        });
    }
};

// 指令处理集合
var compileUtil = {
    text: function(node, vm, exp) {
        this.bind(node, vm, exp, 'text');
    },
    // ...省略
    bind: function(node, vm, exp, dir) {
        var updaterFn = updater[dir + 'Updater'];
        // 第一次初始化视图
        updaterFn && updaterFn(node, vm[exp]);
        // 实例化订阅者,此操作会在对应的属性消息订阅器中添加了该订阅者watcher
        new Watcher(vm, exp, function(value, oldValue) {
            // 一旦属性值有变化,会收到通知执行此更新函数,更新视图
            updaterFn && updaterFn(node, value, oldValue);
        });
    }
};

// 更新函数
var updater = {
    textUpdater: function(node, value) {
        node.textContent = typeof value == 'undefined' ? '' : value;
    }
    // ...省略
};

######这里通过递归遍历保证了每个节点及子节点都会解析编译到,包括了{{}}表达式声明的文本节点。指令的声明规定是通过特定前缀的节点属性来标记,如<span v-text="content" other-attrv-text便是指令,而other-attr不是指令,只是普通的属性。监听数据、绑定更新函数的处理是在compileUtil.bind()这个方法中,通过new Watcher()添加回调来接收数据变化的通知

#####完整代码

function Compile(el, vm) {
    this.$vm = vm;
    this.$el = this.isElementNode(el) ? el : document.querySelector(el);

    if (this.$el) {
        this.$fragment = this.node2Fragment(this.$el);
        this.init();
        this.$el.appendChild(this.$fragment);
    }
}

Compile.prototype = {
    constructor: Compile,
    node2Fragment: function(el) {
        var fragment = document.createDocumentFragment(),
            child;

        // 将原生节点拷贝到fragment
        while (child = el.firstChild) {
            fragment.appendChild(child);
        }

        return fragment;
    },

    init: function() {
        this.compileElement(this.$fragment);
    },

    compileElement: function(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.trim());
            }

            if (node.childNodes && node.childNodes.length) {
                me.compileElement(node);
            }
        });
    },

    compile: function(node) {
        var nodeAttrs = node.attributes,
            me = this;

        [].slice.call(nodeAttrs).forEach(function(attr) {
            var attrName = attr.name;
            if (me.isDirective(attrName)) {
                var exp = attr.value;
                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);
            }
        });
    },

    compileText: function(node, exp) {
        compileUtil.text(node, this.$vm, exp);
    },

    isDirective: function(attr) {
        return attr.indexOf('v-') == 0;
    },

    isEventDirective: function(dir) {
        return dir.indexOf('on') === 0;
    },

    isElementNode: function(node) {
        return node.nodeType == 1;
    },

    isTextNode: function(node) {
        return node.nodeType == 3;
    }
};

// 指令处理集合
var compileUtil = {
    text: function(node, vm, exp) {
        this.bind(node, vm, exp, 'text');
    },

    html: function(node, vm, exp) {
        this.bind(node, vm, exp, 'html');
    },

    model: function(node, vm, exp) {
        this.bind(node, vm, exp, 'model');

        var me = this,
            val = this._getVMVal(vm, exp);
        node.addEventListener('input', function(e) {
            var newValue = e.target.value;
            if (val === newValue) {
                return;
            }

            me._setVMVal(vm, exp, newValue);
            val = newValue;
        });
    },

    class: function(node, vm, exp) {
        this.bind(node, vm, exp, 'class');
    },

    bind: function(node, vm, exp, dir) {
        var updaterFn = updater[dir + 'Updater'];

        updaterFn && updaterFn(node, this._getVMVal(vm, exp));

        new Watcher(vm, exp, function(value, oldValue) {
            updaterFn && updaterFn(node, value, oldValue);
        });
    },

    // 事件处理
    eventHandler: function(node, vm, exp, dir) {
        var eventType = dir.split(':')[1],
            fn = vm.$options.methods && vm.$options.methods[exp];

        if (eventType && fn) {
            node.addEventListener(eventType, fn.bind(vm), false);
        }
    },

    _getVMVal: function(vm, exp) {
        var val = vm;
        exp = exp.split('.');
        exp.forEach(function(k) {
            val = val[k];
        });
        return val;
    },

    _setVMVal: function(vm, exp, value) {
        var val = vm;
        exp = exp.split('.');
        exp.forEach(function(k, i) {
            // 非最后一个key,更新val的值
            if (i < exp.length - 1) {
                val = val[k];
            } else {
                val[k] = value;
            }
        });
    }
};


var updater = {
    textUpdater: function(node, value) {
        node.textContent = typeof value == 'undefined' ? '' : value;
    },

    htmlUpdater: function(node, value) {
        node.innerHTML = typeof value == 'undefined' ? '' : value;
    },

    classUpdater: function(node, value, oldValue) {
        var className = node.className;
        className = className.replace(oldValue, '').replace(/\s$/, '');

        var space = className && String(value) ? ' ' : '';

        node.className = className + space + value;
    },

    modelUpdater: function(node, value, oldValue) {
        node.value = typeof value == 'undefined' ? '' : value;
    }
};

####实现Watcher

Watcher订阅者作为Observer和Compile之间通信的桥梁,主要做的事情是: 1、在自身实例化时往属性订阅器(dep)里面添加自己 2、自身必须有一个update()方法 3、待属性变动dep.notice()通知时,能调用自身的update()方法,并触发Compile中绑定的回调,则功成身退

function Watcher(vm, exp, cb) {
    this.cb = cb;
    this.vm = vm;
    this.exp = exp;
    // 此处为了触发属性的getter,从而在dep添加自己,结合Observer更易理解
    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); // 执行Compile中绑定的回调,更新视图
        }
    },
    get: function() {
        Dep.target = this;    // 将当前订阅者指向自己
        var value = this.vm[exp];    // 触发getter,添加自己到属性订阅器中
        Dep.target = null;    // 添加完毕,重置
        return value;
    }
};
// 这里再次列出Observer和Dep,方便理解
Object.defineProperty(data, key, {
    get: function() {
        // 由于需要在闭包内添加watcher,所以可以在Dep定义一个全局target属性,暂存watcher, 添加完移除
        Dep.target && dep.addDep(Dep.target);
        return val;
    }
    // ... 省略
});
Dep.prototype = {
    notify: function() {
        this.subs.forEach(function(sub) {
            sub.update(); // 调用订阅者的update方法,通知变化
        });
    }
};

######实例化Watcher的时候,调用get()方法,通过Dep.target = watcherInstance标记订阅者是当前watcher实例,强行触发属性定义的getter方法,getter方法执行的时候,就会在属性的订阅器dep添加当前watcher实例,从而在属性值有变化的时候,watcherInstance就能收到更新通知。

完整代码
function Watcher(vm, expOrFn, cb) {
    this.cb = cb;
    this.vm = vm;
    this.expOrFn = expOrFn;
    this.depIds = {};

    if (typeof expOrFn === 'function') {
        this.getter = expOrFn;
    } else {
        this.getter = this.parseGetter(expOrFn.trim());
    }

    this.value = this.get();
}

Watcher.prototype = {
    constructor: Watcher,
    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);
        }
    },
    addDep: function(dep) {
        // 1. 每次调用run()的时候会触发相应属性的getter
        // getter里面会触发dep.depend(),继而触发这里的addDep
        // 2. 假如相应属性的dep.id已经在当前watcher的depIds里,说明不是一个新的属性,仅仅是改变了其值而已
        // 则不需要将当前watcher添加到该属性的dep里
        // 3. 假如相应属性是新的属性,则将当前watcher添加到新属性的dep里
        // 如通过 vm.child = {name: 'a'} 改变了 child.name 的值,child.name 就是个新属性
        // 则需要将当前watcher(child.name)加入到新的 child.name 的dep里
        // 因为此时 child.name 是个新值,之前的 setter、dep 都已经失效,如果不把 watcher 加入到新的 child.name 的dep中
        // 通过 child.name = xxx 赋值的时候,对应的 watcher 就收不到通知,等于失效了
        // 4. 每个子属性的watcher在添加到子属性的dep的同时,也会添加到父属性的dep
        // 监听子属性的同时监听父属性的变更,这样,父属性改变时,子属性的watcher也能收到通知进行update
        // 这一步是在 this.get() --> this.getVMVal() 里面完成,forEach时会从父级开始取值,间接调用了它的getter
        // 触发了addDep(), 在整个forEach过程,当前wacher都会加入到每个父级过程属性的dep
        // 例如:当前watcher的是'child.child.name', 那么child, child.child, child.child.name这三个属性的dep都会加入当前watcher
        if (!this.depIds.hasOwnProperty(dep.id)) {
            dep.addSub(this);
            this.depIds[dep.id] = dep;
        }
    },
    get: function() {
        Dep.target = this;
        var value = this.getter.call(this.vm, this.vm);
        Dep.target = null;
        return value;
    },

    parseGetter: function(exp) {
        if (/[^\w.$]/.test(exp)) return; 

        var exps = exp.split('.');

        return function(obj) {
            for (var i = 0, len = exps.length; i < len; i++) {
                if (!obj) return;
                obj = obj[exps[i]];
            }
            return obj;
        }
    }
};

实现MVVM

######MVVM作为数据绑定的入口,整合Observer、Compile和Watcher三者,通过Observer来监听自己的model数据变化,通过Compile来解析编译模板指令,最终利用Watcher搭起Observer和Compile之间的通信桥梁,达到数据变化 -> 视图更新;视图交互变化(input) -> 数据model变更的双向绑定效果。

function MVVM(options) {
    this.$options = options;
    var data = this._data = this.$options.data;
    observe(data, this);
    this.$compile = new Compile(options.el || document.body, this)
}
//监听的数据对象是options.data,每次需要更新视图,则必须通过
//var vm = new MVVM({data:{name: '原始数据'}}); 
//vm._data.name = '改变数据'。

//期望的调用方式应该是这样的:
//var vm = new MVVM({data: {name: '原始数据'}}); vm.name = '改变数据';

//需要给MVVM实例添加一个属性代理的方法,使访问vm的属性代理为访问vm._data的属性,改造后的代码如下:
//代理
function MVVM(options) {
    this.$options = options;
    var data = this._data = this.$options.data, me = this;
    // 属性代理,实现 vm.xxx -> vm._data.xxx
    Object.keys(data).forEach(function(key) {
        me._proxy(key);
    });
    observe(data, this);
    this.$compile = new Compile(options.el || document.body, this)
}

MVVM.prototype = {
    _proxy: function(key) {
        var me = this;
        Object.defineProperty(me, key, {
            configurable: false,
            enumerable: true,
            get: function proxyGetter() {
                return me._data[key];
            },
            set: function proxySetter(newVal) {
                me._data[key] = newVal;
            }
        });
    }
};