// 事件系统 function Event() { this.events = {}; } Event.prototype.emit = function(attr, val, newVal) { this.events[attr] && this.events[attr].forEach(function(item){ item(val, newVal) }) } Event.prototype.on = function(attr, callback){ if(this.events[attr]){ this.events[attr].push(callback); }else{ this.events[attr] = [callback]; } } function Observer(data) { this.data = data; this.recursion(this.data); this.eventsBus = new Event(); } Observer.prototype.recursion = function(obj) { var val = null; for (key in obj) { if(obj.hasOwnProperty(key)) { val = obj[key]; if(typeof val === 'object' && !!val) { new Observer(val); } this.access(key, val); } } } Observer.prototype.access = function(key, val) { var self = this; Object.defineProperty(this.data, key, { enumerable: true, configurable: true, get: function () { console.log('你访问了' + key); return val }, set: function (newVal) { if (typeof newVal === 'object' && !!newVal) { new Observer(newVal); } console.log('你设置了' + key); console.log('新的' + key + ' = ' + newVal) self.eventsBus.emit(key, val, newVal); if (newVal === val) return; val = newVal } }) } Observer.prototype.$watch = function(attr, callback){ this.eventsBus.on(attr, callback); } let app1 = new Observer({ user: { name: "liangshaofeng", age: "24" }, address: { city: "beijing" } }); app1.data.user.name // 你访问了 name app1.data.user.age = 100; // 你设置了 age,新的值为100 app1.data.user.name = { lastName: 'liang', firstName: 'shaofeng' }; app1.data.user.name.lastName; // 这里还需要输出 '你访问了 lastName ' app1.data.user.name.firstName = 'lalala'; // 这里还需要输出 '你设置了firstName, 新的值为 lalala' var app1 = new Observer({ name: 'liujianhuan', age: 25, company: 'Qihoo 360', address: 'Chaoyang, Beijing' }) app1.$watch('age', function(oldVal, newVal){ console.log(`我的年龄变了,原来是: ${oldVal}岁,现在是:${newVal}岁了`) }) app1.$watch('age', function(oldVal, newVal){ console.log(`我的年龄真的变了诶,竟然年轻了${oldVal - newVal}岁`) }) app1.data.age = 20;
vue实现动态数据绑定(2)
内容版权声明:除非注明,否则皆为本站原创文章。