# Data listeners

A data listener can be used to listen for and respond to changes in any attribute and data field.Support starts with Weixin Mini Program base library version {% version ('2.6.1')%}.

# Use a data listener

Sometimes, some operations need to be performed when some data fields are set by setData.

For example,this.data.sumis always the sum ofthis.data.numberAandthis, data.numberB.At this point, you can implement the following using a data listener.

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

Preview with Developer Tool

# Listening field syntax

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

At the same time, the listener can listen to sub-data fields, 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 sub-data fields, you can use a general parameter**

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, the entire setData can be listened to using only the wildcard`*[[TAA-0-END]].

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

# Note

  • The data monitor listens to the data fields involved in setData, and is triggered even if the values of those data fields do not change.
  • If you use setData in a data monitor function to set the data fields that you listen on, you can cause an endless loop and need special attention.
  • Data monitors are more powerful and usually have better performance than observers for attributes.