学习小程序开发,练习对象属性监听
发布于 4 年前 作者 yang94 4368 次浏览 来自 分享

/**用例

* const {MRegisterObserver,MCancelObserver,MObseverMethod} = require('相对路径/obseverObject.js')

创建监听: let test =new MObseverMethod(监听对象,监听属性,(val)=>{})

注册监听: MRegisterObserver(test);

取消监听: MCancelObserver(test);

* */

obseverObject.js文件

let observerMap = {
  // name:[MObseverMethod]
};

class MObseverMethod {
  constructor(target, name, method) {
    this.method = method;
    this.target = target;
    this.name = name;

    let _key=0;
    this.setKey = (key) => {
      _key = key;
    }
    this.getKey = () => {
      return _key;
    }
  }
}

const initMethodKey = (name) => {
  let lmethonObjs = observerMap[name];
  if (lmethonObjs) {
    let llength = lmethonObjs.length;
    if (llength == 0) {
      return 1;
    } else {
      return lmethonObjs[llength - 1].getKey() + 1;
    }
  } else {
    return 1;
  }
}

const MRegisterObserver = (omethod) => {
  let target = omethod.target;
  let name = omethod.name
  if (!observerMap[name]) {
    observerMap[name] = [];
  } 
  let obsObjs = observerMap[name];
  //
  if(omethod.getKey()==0){
    omethod.setKey(initMethodKey(name));
    obsObjs.push(omethod);
    observerMap[name] = obsObjs;
  }
  // 
  var val = target[name];
  let obsFuns = observerMap[name];

  Object.defineProperty(target, name, {
    configurable: true,
    enumerable: true,
    set: function (value) {
      val = value;
      obsFuns.map((oFuns) => oFuns.method(value));
    },
    get: function () {
      return val;
    }
  });
}
const MCancelObserver = (omethod) => {
  let name = omethod.name
  if (observerMap[name]) {
    let obsObjs = observerMap[name];
    for (let i = 0; i < obsObjs.length; i++) {
      let obsObj = obsObjs[i];
      if (obsObj.getKey() == omethod.getKey()) {
        obsObjs.splice(i, 1);
        observerMap[name] = obsObjs;
        break;
      }
    }
  }
}

module.exports = {
  MRegisterObserver,
  MCancelObserver,
  MObseverMethod
}

回到顶部