目录

Observers for Data Listening

Use observers to listen for and respond to any changes of properties and data fields.

How to Use

When using setData to set some data fields, it is often necessary to synchronize other data as well.

For example, this.data.sum is the sum of this.data.numberOne and this.data.numberTwo. When either the value of numberOne or numberTwo changes, the value of sum needs to be recalculated. In this case, you can use observers to achieve this.

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

Listening Fields

Observers support listening for properties or data changes. They can simultaneously monitor multiple fields, but each observer can be triggered only once per setData call. Besides, you can use observers to listen for subfield changes.

The sample code is as follows:

Component({
  observers: {
    'obj.field': function(field) {
      // Triggered when setData is used to set this.data.obj.field.
      // Triggered also when setData is used to set this.data.obj.
      field === this.data.obj.field;
    },
    'arr[10]': function(arr10) {
      // Triggered when setData is used to set this.data.arr[10].
      // Triggered when setData is used to set this.data.arr.
      arr10 === this.data.arr[10];
    }
  }
});

To listen for subfield changes of an object, you can use the wildcard **.

Component({
  observers: {
    'obj.field.**': function(field) {
      // Triggered when setData is used to set this.data.obj.field or any subfield under this.data.obj.field.
      // Triggered also when setData is used to set this.data.obj.
      field === this.data.obj.field;
    }
  },
  ready: function() {
    // This will trigger the preceding observer.
    this.setData({
      'obj.field': {}
    });
    // This will also trigger the preceding observer.
    this.setData({
      'obj.field.xxx': {}
    });
    // This still triggers the preceding observer.
    this.setData({
      obj: {}
    });
  }
});

Additionally, using the wildcard ** enables listening for all changes introduced by setData.

Component({
  observers: {
    '**': function() {
      // Triggered each time setData is called.
    }
  }
});