Define and use data listeners
Data listeners can be employed to monitor and respond to alterations in any attribute or data field. Occasionally, certain actions need to be executed when some data fields are set by setData. For instance, this.data.sum is the sum of this.data.numberA and this.data.numberB. At this point, data listeners can be used to accomplish such operations.
Component({
attached: function() {
this.setData({
numberA: 1,
numberB: 2,
})
},
observers: {
'numberA, numberB': function(numberA, numberB) {
// Execute this function when either numberA or numberB is set.
this.setData({
sum: numberA + numberB
})
}
}
})
Syntax of monitored fields
Data listeners facilitate the monitoring of changes in attributes or internal data, with the capacity to observe multiple changes simultaneously. Each listener is triggered at most once per setData operation. Moreover, listeners can monitor sub-data fields, as demonstrated in the following example.
Component({
observers: {
'some.subfield': function(subfield) {
// Triggered when this.data.some.subfield is set using setData.
// (In addition, setting this.data.some with setData will also trigger it.)
subfield === this.data.some.subfield
},
'arr[12]': function(arr12) {
// Triggered when this.data.arr[12] is set using setData
// (Additionally, setting this.data.arr with setData will also trigger it.)
arr12 === this.data.arr[12]
},
}
})
To monitor changes in all sub-data fields, the wildcard ** can be used.
Component({
observers: {
'some.field.**': function(field) {
// Triggered when this.data.some.field itself or any of its sub-data fields are set using setData.
// (In addition, setting this.data.some with setData will also trigger it.)
field === this.data.some.field
},
},
attached: function() {
// This will trigger the aforementioned listener.
this.setData({
'some.field': { /* ... */ }
})
// This will also trigger the aforementioned listener.
this.setData({
'some.field.xxx': { /* ... */ }
})
// This will nonetheless trigger the aforementioned listener.
this.setData({
'some': { /* ... */ }
})
}
})
Moreover, if only the wildcard ** is used, it can monitor all setData operations.
Component({
observers: {
'**': function() {
// Triggered with each setData operation.
},
},
}
Note:
The data listener monitors the data fields involved in setData operations. Even if the values of these data fields do not change, the data listener will still be triggered.
If setData is used within the data listener function to set the data fields it is monitoring, it may lead to an infinite loop, which requires special attention.
Compared to the attribute listener, the data listener is more powerful and typically offers superior performance.
Was this page helpful?