微信小程序watch 属性监听器

   /**
   * 设置监听器 接收需要监听的对象, 一个watch对象
   */
  setWatcher(data, watch) {
    Object.keys(watch).forEach(v => { // 遍历需要监听的属性
        this.observe(data, v, watch[v]); // 监听data内的v属性,传入watch内对应函数以调用
    })
  },
/**
   * 监听属性 并执行监听函数
   */
  observe(obj, key, watchFun) {
    var val = obj[key]; // 给该属性设默认值
    Object.defineProperty(obj, key, {
        configurable: true,
        enumerable: true,
        set: function(value) {
            val = value;
            watchFun(value,val); // 赋值(set)时,调用对应函数
        },
        get: function() {
            return val;
        }
    })
  },

使用 

在onload中调用app.setWatcher(app.globalData, this.watch())

 watch() {
    return {
      onceMsg: (newVal) => {
        if(newVal.from === this.data.userName) {
          app.globalData.nim.sendMsgReceipt({
            msg: newVal
          });
          if(newVal.type === 'text') {
            newVal.nodes = this.generateRichTextNode(newVal.text);
          }
          newVal.isRead = app.globalData.nim.isMsgRemoteRead(newVal);
          let list = this.data.historyList;
          list.push(newVal);
          this.setData({
            historyList: list
          })
        }
      }
    }
  },

 


版权声明:本文为liux6687原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。