console.log(`info after change name: ${this.info.name}, age: ${this.info.age} `);
}
onNumArrChange() {
console.log(`numArr after change ${JSON.stringify(this.numArr)}`);
}
build() {
Row() {
Column() {
Button("change info name")
.onClick(() => {
this.info.name = "Jack";
})
Button("change info age")
.onClick(() => {
this.info.age = 30;
})
Button("change numArr[2]")
.onClick(() => {
this.numArr[2] = 5;
})
Button("change numArr[3]")
.onClick(() => {
this.numArr[3] = 6;
})
}
.width('100%')
}
.height('100%')
}
}
复制代码
上述代码中,点击"change info name"更改info中的name属性或点击"change info age"更改age时,均会触发info注册的@Watch回调。点击"change numArr[2]"更改numArr中的第3个元素或点击"change numArr[3]"更改第4个元素时,均会触发numArr注册的@Watch回调。在这两个回调中,由于无法获取数据更改前的值,在业务逻辑更加复杂的场景下,无法精确知道是哪一个属性或元素发生了改变从而触发了@Watch事故,这不便于开辟者对变量的更改进行精确监听。因此推出@Monitor装饰器实现对对象、数组中某一单个属性或数组项变化的监听,并且能够获取到变化之前的值。
装饰器说明
在点击按钮"change count to 1000"后,会触发一次onCountChange方法,并输出日志"count change from 0 to 1000"。在点击按钮"change count to 0 then to 1000"后,由于事故前后属性count的值并没有改变,都为1000,所以不触发onCountChange方法。
限定条件
当Index组件创建Info类实例时,日志输出in constructor message change to initialized。此时Index组件的@Monitor还未初始化成功,因此不会监听到message的变化。
当Index组件创建完成,页面加载完成后,点击按钮“change message in Index”,此时Index组件中的@Monitor能够监听到变化,日志输出Index message change from initialized to Index click to change Message。
点击按钮“show/hide Child”,创建Child组件,在Child组件初始化@Param装饰的变量以及@Monitor之后,调用Child组件的aboutToAppear回调,改变message。此时Index组件与Child组件的@Monitor均能监听到变化,日志输出Index message change from Index click to change Message to Child aboutToAppear以及Child message change from Index click to change Message to Child aboutToAppear。
点击按钮“change message in Child”,改变message。此时Index组件与Child组件的@Monitor均能监听到变化,日志输出Index message change from Child aboutToAppear to Child click to change Message以及Child message change from Child aboutToAppear to Child click to change Message。
点击按钮”show/hide Child“,销毁Child组件,调用Child组件的aboutToDisappear回调,改变message。此时Index组件与Child组件的@Monitor均能监听到变化,日志输出Child aboutToDisappear,Index message change from Child click to change Message to Child aboutToDisappear以及Child message change from Child click to change Message to Child aboutToDisappear。
点击按钮“change message in Index”,改变message。此时Child组件已销毁,其注册的@Monitor监听也被解注册,仅有Index组件的@Monitor能够监听到变化,日志输出Index message change from Child aboutToDisappear to Index click to change Message。