js 对象数据观察者实现
var observer = function (originalData) { var newData = {}; newData.observer = {}; newData.$data = {}; for (var key in originalData) { (function (key) { newData.$data[key] = originalData[key]; Object.defineProperty(newData, key, { set: function (val) { newData.$data[key] = val; this.dispatch(key, val); }, get: function () { return newData.$data[key]; } }); newData.observer[key] = []; })(key); } newData.on = function (key, callback) { newData.observer[key].push(callback); }; newData.dispatch = function (key, val) { for (var i in newData.observer[key]) { newData.observer[key][i](val); } }; return newData; }; var data = observer({age: 1, name: 'mahuan'}); data.on('name', function (val) { console.log('hello, ' + val); }); data.on('age', function (val) { console.log('oh, you are ' + val); }); data.name = "mahuan"; data.age = 3;
hello, mahuan
oh, you are 3