javascript观察者模式实现自动刷新效果
时间:2021-08-30 10:03:40|栏目:JavaScript代码|点击: 次
本文实例为大家分享了js观察者模式实现自动刷新的具体代码,供大家参考,具体内容如下
// author wangbinandi@gmail.com const observable = obj => { const observers = Symbol(); const set = function(target, key, value) { const result = Reflect.set(target, key, value); //console.log("set key:" + key); if ( target[observers].has(key) ) { target[observers].get(key).forEach(observer => observer()); } return result; } const get = function(target, key) { const result = Reflect.get(target, key); //console.log("get key:" + key); if (arguments.callee.caller) { if (!target[observers].has(key)) { target[observers].set(key, new Set()) } target[observers].get(key).add(arguments.callee.caller); } return result; } obj[observers] = new Map(); // string => Set() return new Proxy(obj, {set, get}); }; const autorun = fn => fn(); var person = observable({ firstName: 'Matt', lastName: 'Ruby', age: 18, weight: 50 }); autorun(function () { console.log('autorun.getAge: ' + person.firstName + ' ' + person.age); }); autorun(function () { console.log('autorun.getName: ' + person.firstName + ' ' + person.lastName); }); person.age = 19; person.weight = 55; person.firstName = 'test'; person.lastName = 'MyLast'; console.log(person.lastName); person.age = 20;
栏 目:JavaScript代码
下一篇:关于document.cookie的使用javascript
本文地址:http://www.codeinn.net/misctech/171150.html