Record icon indicating copy to clipboard operation
Record copied to clipboard

通过 Object.defineProperty 监听属性值的变化

Open HerryLo opened this issue 7 years ago • 0 comments

var data = {
      name: 'kindeng'
};

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;
        }
    });
}

observe(data);
data.name = 'dmq'; 

HerryLo avatar Jul 24 '19 02:07 HerryLo