# Data listener

Data listeners can be used to listen for and respond to changes in any property and data field. Mini Program base library version 2.6.1 Start supporting.

# Use Data Listener

Sometimes, after some data fields are setData Setup, there are some operations that need to be performed.

For example, this.data.sum Always. this.data.numberA and this.data.numberB Of and. At this point, you can use the data listener for the following implementation.

Component({
  attached: function() {
    this.setData({
      numberA: 1,
      numberB: 2,
    })
  },
  observers: {
    'numberA, numberB': function(numberA, numberB) {
      // in numberA or numberB Is set, execute this function
      this.setData({
        sum: numberA + numberB
      })
    }
  }
})

{% Minicode ('FUZF9ams7g6N') %}

# Listening field syntax

A data listener supports listening for changes in attributes or internal data, and can listen for more than one at a time. first setData Fire each listener at most once.

At the same time, listeners can listen on subdata fields, as shown in the following example.

Component({
  observers: {
    'some.subfield': function(subfield) {
      // use setData Set up this.data.some.subfield Time trigger
      // (In addition, the use of setData Set up this.data.some Will also trigger)
      subfield === this.data.some.subfield
    },
    'arr[12]': function(arr12) {
      // use setData Set up this.data.arr[12] Time trigger
      // (In addition, the use of setData Set up this.data.arr Will also trigger)
      arr12 === this.data.arr[12]
    },
  }
})

If you need to listen for changes in all child data fields, you can use wildcards **

Component({
  observers: {
    'some.field.**': function(field) {
      // use setData Set up this.data.some.field Itself or any of the subdata fields under it when triggered
      // (In addition, the use of setData Set up this.data.some Will also trigger)
      field === this.data.some.field
    },
  },
  attached: function() {
    // This will trigger the upper observer
    this.setData({
      'some.field': { /* ... */ }
    })
    // This will also trigger the above observer
    this.setData({
      'some.field.xxx': { /* ... */ }
    })
    // That's still gonna trigger the top. observer
    this.setData({
      'some': { /* ... */ }
    })
  }
})

In particular, using only wildcards ** Can listen to all of them. setData 。

Component({
  observers: {
    '**': function() {
      // every time setData Both trigger
    },
  },
})

# Note

  • The data listener listens setData The data fields involved, even if the values of these data fields have not changed, the data listener will still be triggered.
  • If you use it in a data listener function setData Setting the data field itself to listen to can lead to endless loops and requires special attention.
  • Of the data listener and attribute observer Data listeners are more powerful and generally have better performance.