Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

WeChat small program data listener


May 17, 2021 WeChat Mini Program Development Document


Table of contents


The data listener

Data listeners can be used to listen for and respond to changes in any property and data fields. Support starts with the small program base library version 2.6.1.

Use a data listener

Sometimes, when some data fields are set up by setData, something needs to be done.

For example, this.data.sum is always the sum of this.data.numberA and this.data.numberB. At this point, you can use a data listener to do the following.

Component({
  attached: function() {
    this.setData({
      numberA: 1,
      numberB: 2,
    })
  },
  observers: {
    'numberA, numberB': function(numberA, numberB) {
      // 在 numberA 或者 numberB 被设置时,执行这个函数
      this.setData({
        sum: numberA + numberB
      })
    }
  }
})

Listen to the field syntax

Data listeners support changes in listening properties or internal data and can listen to multiple at the same time. SetData is triggered up to one per listener at a time.

At the same time, the listener can listen for subdies, as shown in the following example.

Component({
  observers: {
    'some.subfield': function(subfield) {
      // 使用 setData 设置 this.data.some.subfield 时触发
      // (除此以外,使用 setData 设置 this.data.some 也会触发)
      subfield === this.data.some.subfield
    },
    'arr[12]': function(arr12) {
      // 使用 setData 设置 this.data.arr[12] 时触发
      // (除此以外,使用 setData 设置 this.data.arr 也会触发)
      arr12 === this.data.arr[12]
    },
  }
})

If you need to listen for changes in all child data fields, you can use the wildcard .

Component({
  observers: {
    'some.field.**': function(field) {
      // 使用 setData 设置 this.data.some.field 本身或其下任何子数据字段时触发
      // (除此以外,使用 setData 设置 this.data.some 也会触发)
      field === this.data.some.field
    },
  },
  attached: function() {
    // 这样会触发上面的 observer
    this.setData({
      'some.field': { /* ... */ }
    })
    // 这样也会触发上面的 observer
    this.setData({
      'some.field.xxx': { /* ... */ }
    })
    // 这样还是会触发上面的 observer
    this.setData({
      'some': { /* ... */ }
    })
  }
})

In particular, you can listen to all setDatas using only wildcards.

Component({
  observers: {
    '**': function() {
      // 每次 setData 都触发
    },
  },
})

Tips:

  • The data listener listens to the data fields involved in setData, and even if the values of those data fields do not change, the data listener is triggered.
  • If you use setData in a data listener function to set up the data fields that you listen to, you may cause a dead loop that requires special attention.
  • Data listeners are more powerful and typically perform better than observers of properties.