vue源码进修之简朴的数据监听

先完成一个简朴的数据挟制。
思绪:

  1. 遍历对象的每一个属性,为每一个属性挂上监听函数(即应用Object.defineProperty举行元编程);

  2. 斟酌属性的子属性的监听;
    先上代码:


function Observer(data) {
    this.data = data;
    this.walk(data);
}
Observer.prototype.walk = function(obj) {
    var val;
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            val = obj[key];

            if (obj[key] instanceof Object) {
                new Observer(obj[key]);
            }

            this.convert(key, val);
        }
    }
}
Observer.prototype.convert = function(key, val) {
    Object.defineProperty(this.data, key, {
        enumerable: true,
        configurable: true,
        get: function() {
            console.log('你访问了' + key);
            return val;
        },
        set: function(newVal) {
            console.log('你设置了' + key);
            console.log('新的' + key + '=' + newVal);
            if (val === newVal) {
                return;
            }
            val = newVal;
        }
    });
}
var data = {
    user: {
        name: "lixixi",
        age: "24"
    },
    address: {
        city: "beijing"
    }
};

var app = new Observer(data);

个中触及的知识点:

  1. Object.defineProperty(object, key, {});

  2. 假如属性值照样对象,则递归继承new Observer;

    原文作者:Alex
    原文地址: https://segmentfault.com/a/1190000008780394
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞