先完成一个简朴的数据挟制。
思绪:
遍历对象的每一个属性,为每一个属性挂上监听函数(即应用Object.defineProperty举行元编程);
斟酌属性的子属性的监听;
先上代码:
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);
个中触及的知识点:
Object.defineProperty(object, key, {});
假如属性值照样对象,则递归继承new Observer;