今天遇到个需求,需要在组件中对 properties 数据进行监听,如果 properties 数据改变的话,就执行相应的回调函数。
在微信小程序中,我们可以在组件的构造对象中定义 observers 字段对数据进行监听。
Component({
attached: function() {
this.setData({
numberA: 1,
numberB: 2,
})
},
observers: {
'numberA, numberB': function(numberA, numberB) {
// 在 numberA 或者 numberB 被设置时,执行这个函数
this.setData({
sum: numberA + numberB
})
}
}
})
而在抖音小程序中,并没有提供 observers,而是提供了和 observers 类似的特性。
对应的官方文档看这里:Component 构造器
我们可以在某个 properties 数据的定义对象中定义对应的 observer 回调函数。当该 properties 数据发生变化的时候,会触发执行该回调函数。
Component({
behaviors: [],
properties: {
myProperty: {
// Type (required), currently accepted types include: String, Number, Boolean, Object, Array, null (indicating any type)
type: String,
// The initial value of the attribute (optional), if not specified, one will be selected according to the type
value: '',
// The function (optional) executed when the property is changed can also be written as the method name string defined in the methods section, such as:'_myPropertyChange'
observer: function(newVal, oldVal) {
// Usually newVal is the newly set data, oldVal is the old data
}
},
myPropertyB: String // Simplified definition
}
})