富贵资源网 Design By www.hznty.com

本文实例为大家分享了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;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com