Data Listener

Data listener is used to monitor and respond to changes in any properties or data fields, which is supported as of Mini Program base library 2.6.1.

Using Data Listener

When certain data fields are set via setData, some operations must be executed.

For example, this.data.sum is always the sum of this.data.numberA and this.data.numberB. In this case, you can use a data listener to implement the following operation:

Component({
  attached: function() {
    this.setData({
      numberA: 1,
      numberB: 2,
    })
  },
  observers: {
    'numberA, numberB': function(numberA, numberB) {
      // Execute this function when numberA or numberB is set
      this.setData({
        sum: numberA + numberB
      })
    }
  }
})

Preview with Developer Tool

Field Listening Syntax

Data listeners can monitor multiple changes to properties or internal data simultaneously. A listener can only be triggered one time by a setData operation.

Listeners can also monitor sub-data fields, as shown below.

Component({
  observers: {
    'some.subfield': function(subfield) {
      // Triggered when this.data.some.subfield is set via setData
      // (Also triggered when this.data.some is set via setData)
      subfield === this.data.some.subfield
    },
    'arr[12]': function(arr12) {
      // Triggered when this.data.arr[12] is set via setData
      // (Also triggered when this.data.arr is set via setData)
      arr12 === this.data.arr[12]
    },
  }
})

To monitor changes to all sub-data fields, you can use a wildcard **.

Component({
  observers: {
    'some.field.**': function(field) {
      // Triggered when setData is used to set this.data.some.field itself or any of its sub-data fields
      // (Also triggered when this.data.some is set via setData)
      field === this.data.some.field
    },
  },
  attached: function() {
    // This will trigger the above observer
    this.setData({
      'some.field': { /* ... */ }
    })
    // This will also trigger the above observer
    this.setData({
      'some.field.xxx': { /* ... */ }
    })
    // This will still trigger the above observer
    this.setData({
      'some': { /* ... */ }
    })
  }
})

You can simply use the wildcard ** to monitor all setData.

Component({
  observers: {
    '**': function() {
      // Triggered upon each setData operation
    },
  },
})

Bugs & Tips:

  • Data listeners monitor the data fields set via setData. Even if the values of these data fields do not change, the data listeners will still be triggered.
  • Be aware that, if you use setData to set the monitored data fields in the data listener function, this can create an infinite loop.
  • Compared to a property observer, a data listener is more powerful with better performance.