1# \@Observed装饰器和\@ObjectLink装饰器:嵌套类对象属性变化 2 3 4上文所述的装饰器仅能观察到第一层的变化,但是在实际应用开发中,应用会根据开发需要,封装自己的数据模型。对于多层嵌套的情况,比如二维数组,或者数组项class,或者class的属性是class,他们的第二层的属性变化是无法观察到的。这就引出了\@Observed/\@ObjectLink装饰器。 5 6 7> **说明:** 8> 9> 从API version 9开始,这两个装饰器支持在ArkTS卡片中使用。 10 11 12## 概述 13 14\@ObjectLink和\@Observed类装饰器用于在涉及嵌套对象或数组的场景中进行双向数据同步: 15 16- 被\@Observed装饰的类,可以被观察到属性的变化; 17 18- 子组件中\@ObjectLink装饰器装饰的状态变量用于接收\@Observed装饰的类的实例,和父组件中对应的状态变量建立双向数据绑定。这个实例可以是数组中的被\@Observed装饰的项,或者是class object中的属性,这个属性同样也需要被\@Observed装饰。 19 20- 单独使用\@Observed是没有任何作用的,需要搭配\@ObjectLink或者[\@Prop](arkts-prop.md)使用。 21 22 23## 限制条件 24 25使用\@Observed装饰class会改变class原始的原型链,\@Observed和其他类装饰器装饰同一个class可能会带来问题。 26 27## 装饰器说明 28 29| \@Observed类装饰器 | 说明 | 30| -------------- | --------------------------------- | 31| 装饰器参数 | 无 | 32| 类装饰器 | 装饰class。需要放在class的定义前,使用new创建类对象。 | 33 34| \@ObjectLink变量装饰器 | 说明 | 35| ----------------- | ---------------------------------------- | 36| 装饰器参数 | 无 | 37| 同步类型 | 不与父组件中的任何类型同步变量。 | 38| 允许装饰的变量类型 | 必须为被\@Observed装饰的class实例,必须指定类型。<br/>不支持简单类型,可以使用[\@Prop](arkts-prop.md)。<br/>支持继承Date或者Array的class实例,示例见[观察变化](#观察变化)。<br/>支持\@Observed装饰类和undefined或null组成的联合类型,比如ClassA \| ClassB, ClassA \| undefined 或者 ClassA \| null, 示例见[@ObjectLink支持联合类型](#objectlink支持联合类型)。<br/>\@ObjectLink的属性是可以改变的,但是变量的分配是不允许的,也就是说这个装饰器装饰变量是只读的,不能被改变。 | 39| 被装饰变量的初始值 | 不允许。 | 40 41\@ObjectLink装饰的数据为可读示例。 42 43 44```ts 45// 允许@ObjectLink装饰的数据属性赋值 46this.objLink.a= ... 47// 不允许@ObjectLink装饰的数据自身赋值 48this.objLink= ... 49``` 50 51> **说明:** 52> 53> \@ObjectLink装饰的变量不能被赋值,如果要使用赋值操作,请使用[@Prop](arkts-prop.md)。 54> 55> - \@Prop装饰的变量和数据源的关系是是单向同步,\@Prop装饰的变量在本地拷贝了数据源,所以它允许本地更改,如果父组件中的数据源有更新,\@Prop装饰的变量本地的修改将被覆盖; 56> 57> - \@ObjectLink装饰的变量和数据源的关系是双向同步,\@ObjectLink装饰的变量相当于指向数据源的指针。禁止对\@ObjectLink装饰的变量赋值,如果一旦发生\@ObjectLink装饰的变量的赋值,则同步链将被打断。因为\@ObjectLink修饰的变量通过数据源(Object)引用来初始化。对于实现双向数据同步的@ObjectLink,赋值相当于更新父组件中的数组项或者class的属性,TypeScript/JavaScript不能实现,会发生运行时报错。 58 59 60## 变量的传递/访问规则说明 61 62| \@ObjectLink传递/访问 | 说明 | 63| ----------------- | ---------------------------------------- | 64| 从父组件初始化 | 必须指定。<br/>初始化\@ObjectLink装饰的变量必须同时满足以下场景:<br/>- 类型必须是\@Observed装饰的class。<br/>- 初始化的数值需要是数组项,或者class的属性。<br/>- 同步源的class或者数组必须是\@State,\@Link,\@Provide,\@Consume或者\@ObjectLink装饰的数据。<br/>同步源是数组项的示例请参考[对象数组](#对象数组)。初始化的class的示例请参考[嵌套对象](#嵌套对象)。 | 65| 与源对象同步 | 双向。 | 66| 可以初始化子组件 | 允许,可用于初始化常规变量、\@State、\@Link、\@Prop、\@Provide | 67 68 69 **图1** 初始化规则图示 70 71 72 73 74 75## 观察变化和行为表现 76 77 78### 观察变化 79 80\@Observed装饰的类,如果其属性为非简单类型,比如class、Object或者数组,也需要被\@Observed装饰,否则将观察不到其属性的变化。 81 82 83```ts 84class ClassA { 85 public c: number; 86 87 constructor(c: number) { 88 this.c = c; 89 } 90} 91 92@Observed 93class ClassB { 94 public a: ClassA; 95 public b: number; 96 97 constructor(a: ClassA, b: number) { 98 this.a = a; 99 this.b = b; 100 } 101} 102``` 103 104以上示例中,ClassB被\@Observed装饰,其成员变量的赋值的变化是可以被观察到的,但对于ClassA,没有被\@Observed装饰,其属性的修改不能被观察到。 105 106 107```ts 108@ObjectLink b: ClassB 109 110// 赋值变化可以被观察到 111this.b.a = new ClassA(5) 112this.b.b = 5 113 114// ClassA没有被@Observed装饰,其属性的变化观察不到 115this.b.a.c = 5 116``` 117 118\@ObjectLink:\@ObjectLink只能接收被\@Observed装饰class的实例,可以观察到: 119 120- 其属性的数值的变化,其中属性是指Object.keys(observedObject)返回的所有属性,示例请参考[嵌套对象](#嵌套对象)。 121 122- 如果数据源是数组,则可以观察到数组item的替换,如果数据源是class,可观察到class的属性的变化,示例请参考[对象数组](#对象数组)。 123 124继承Date的class时,可以观察到Date整体的赋值,同时可通过调用Date的接口`setFullYear`, `setMonth`, `setDate`, `setHours`, `setMinutes`, `setSeconds`, `setMilliseconds`, `setTime`, `setUTCFullYear`, `setUTCMonth`, `setUTCDate`, `setUTCHours`, `setUTCMinutes`, `setUTCSeconds`, `setUTCMilliseconds` 更新Date的属性。 125 126```ts 127@Observed 128class DateClass extends Date { 129 constructor(args: number | string) { 130 super(args) 131 } 132} 133 134@Observed 135class ClassB { 136 public a: DateClass; 137 138 constructor(a: DateClass) { 139 this.a = a; 140 } 141} 142 143@Component 144struct ViewA { 145 label: string = 'date'; 146 @ObjectLink a: DateClass; 147 148 build() { 149 Column() { 150 Button(`child increase the day by 1`) 151 .onClick(() => { 152 this.a.setDate(this.a.getDate() + 1); 153 }) 154 DatePicker({ 155 start: new Date('1970-1-1'), 156 end: new Date('2100-1-1'), 157 selected: this.a 158 }) 159 } 160 } 161} 162 163@Entry 164@Component 165struct ViewB { 166 @State b: ClassB = new ClassB(new DateClass('2023-1-1')); 167 168 build() { 169 Column() { 170 ViewA({ label: 'date', a: this.b.a }) 171 172 Button(`parent update the new date`) 173 .onClick(() => { 174 this.b.a = new DateClass('2023-07-07'); 175 }) 176 Button(`ViewB: this.b = new ClassB(new DateClass('2023-08-20'))`) 177 .onClick(() => { 178 this.b = new ClassB(new DateClass('2023-08-20')); 179 }) 180 } 181 } 182} 183``` 184 185 186### 框架行为 187 1881. 初始渲染: 189 1. \@Observed装饰的class的实例会被不透明的代理对象包装,代理了class上的属性的setter和getter方法 190 2. 子组件中\@ObjectLink装饰的从父组件初始化,接收被\@Observed装饰的class的实例,\@ObjectLink的包装类会将自己注册给\@Observed class。 191 1922. 属性更新:当\@Observed装饰的class属性改变时,会走到代理的setter和getter,然后遍历依赖它的\@ObjectLink包装类,通知数据更新。 193 194 195## 使用场景 196 197 198### 嵌套对象 199 200以下是嵌套类对象的数据结构。 201 202 203```ts 204// objectLinkNestedObjects.ets 205let NextID: number = 1; 206 207@Observed 208class ClassA { 209 public id: number; 210 public c: number; 211 212 constructor(c: number) { 213 this.id = NextID++; 214 this.c = c; 215 } 216} 217 218@Observed 219class ClassB { 220 public a: ClassA; 221 222 constructor(a: ClassA) { 223 this.a = a; 224 } 225} 226 227@Observed 228class ClassD { 229 public c: ClassC; 230 231 constructor(c: ClassC) { 232 this.c = c; 233 } 234} 235 236@Observed 237class ClassC extends ClassA { 238 public k: number; 239 240 constructor(k: number) { 241 // 调用父类方法对k进行处理 242 super(k); 243 this.k = k; 244 } 245} 246``` 247 248 249 以下组件层次结构呈现的是此数据结构 250 251```ts 252@Component 253struct ViewC { 254 label: string = 'ViewC1'; 255 @ObjectLink c: ClassC; 256 257 build() { 258 Row() { 259 Column() { 260 Text(`ViewC [${this.label}] this.a.c = ${this.c.c}`) 261 .fontColor('#ffffffff') 262 .backgroundColor('#ff3fc4c4') 263 .height(50) 264 .borderRadius(25) 265 Button(`ViewC: this.c.c add 1`) 266 .backgroundColor('#ff7fcf58') 267 .onClick(() => { 268 this.c.c += 1; 269 console.log('this.c.c:' + this.c.c) 270 }) 271 } 272 .width(300) 273 } 274} 275} 276 277@Entry 278@Component 279struct ViewB { 280 @State b: ClassB = new ClassB(new ClassA(0)); 281 @State child : ClassD = new ClassD(new ClassC(0)); 282 build() { 283 Column() { 284 ViewC({ label: 'ViewC #3', c: this.child.c}) 285 Button(`ViewC: this.child.c.c add 10`) 286 .backgroundColor('#ff7fcf58') 287 .onClick(() => { 288 this.child.c.c += 10 289 console.log('this.child.c.c:' + this.child.c.c) 290 }) 291 } 292 } 293} 294``` 295 296被@Observed装饰的ClassC类,可以观测到继承基类的属性的变化。 297 298 299ViewB中的事件句柄: 300 301 302- this.child.c = new ClassA(0) 和this.b = new ClassB(new ClassA(0)): 对\@State装饰的变量b和其属性的修改。 303 304- this.child.c.c = ... :该变化属于第二层的变化,[@State](arkts-state.md#观察变化)无法观察到第二层的变化,但是ClassA被\@Observed装饰,ClassA的属性c的变化可以被\@ObjectLink观察到。 305 306 307ViewC中的事件句柄: 308 309 310- this.c.c += 1:对\@ObjectLink变量a的修改,将触发Button组件的刷新。\@ObjectLink和\@Prop不同,\@ObjectLink不拷贝来自父组件的数据源,而是在本地构建了指向其数据源的引用。 311 312- \@ObjectLink变量是只读的,this.a = new ClassA(...)是不允许的,因为一旦赋值操作发生,指向数据源的引用将被重置,同步将被打断。 313 314 315### 对象数组 316 317对象数组是一种常用的数据结构。以下示例展示了数组对象的用法。 318 319 320```ts 321@Component 322struct ViewA { 323 // 子组件ViewA的@ObjectLink的类型是ClassA 324 @ObjectLink a: ClassA; 325 label: string = 'ViewA1'; 326 327 build() { 328 Row() { 329 Button(`ViewA [${this.label}] this.a.c = ${this.a.c} +1`) 330 .onClick(() => { 331 this.a.c += 1; 332 }) 333 } 334 } 335} 336 337@Entry 338@Component 339struct ViewB { 340 // ViewB中有@State装饰的ClassA[] 341 @State arrA: ClassA[] = [new ClassA(0), new ClassA(0)]; 342 343 build() { 344 Column() { 345 ForEach(this.arrA, 346 (item: ClassA) => { 347 ViewA({ label: `#${item.id}`, a: item }) 348 }, 349 (item: ClassA): string => item.id.toString() 350 ) 351 // 使用@State装饰的数组的数组项初始化@ObjectLink,其中数组项是被@Observed装饰的ClassA的实例 352 ViewA({ label: `ViewA this.arrA[first]`, a: this.arrA[0] }) 353 ViewA({ label: `ViewA this.arrA[last]`, a: this.arrA[this.arrA.length-1] }) 354 355 Button(`ViewB: reset array`) 356 .onClick(() => { 357 this.arrA = [new ClassA(0), new ClassA(0)]; 358 }) 359 Button(`ViewB: push`) 360 .onClick(() => { 361 this.arrA.push(new ClassA(0)) 362 }) 363 Button(`ViewB: shift`) 364 .onClick(() => { 365 this.arrA.shift() 366 }) 367 Button(`ViewB: chg item property in middle`) 368 .onClick(() => { 369 this.arrA[Math.floor(this.arrA.length / 2)].c = 10; 370 }) 371 Button(`ViewB: chg item property in middle`) 372 .onClick(() => { 373 this.arrA[Math.floor(this.arrA.length / 2)] = new ClassA(11); 374 }) 375 } 376 } 377} 378``` 379 380- this.arrA[Math.floor(this.arrA.length/2)] = new ClassA(..) :该状态变量的改变触发2次更新: 381 1. ForEach:数组项的赋值导致ForEach的[itemGenerator](arkts-rendering-control-foreach.md#接口描述)被修改,因此数组项被识别为有更改,ForEach的item builder将执行,创建新的ViewA组件实例。 382 2. ViewA({ label: `ViewA this.arrA[first]`, a: this.arrA[0] }):上述更改改变了数组中第一个元素,所以绑定this.arrA[0]的ViewA将被更新; 383 384- this.arrA.push(new ClassA(0)) : 将触发2次不同效果的更新: 385 1. ForEach:新添加的ClassA对象对于ForEach是未知的[itemGenerator](arkts-rendering-control-foreach.md#接口描述),ForEach的item builder将执行,创建新的ViewA组件实例。 386 2. ViewA({ label: `ViewA this.arrA[last]`, a: this.arrA[this.arrA.length-1] }):数组的最后一项有更改,因此引起第二个ViewA的实例的更改。对于ViewA({ label: `ViewA this.arrA[first]`, a: this.arrA[0] }),数组的更改并没有触发一个数组项更改的改变,所以第一个ViewA不会刷新。 387 388- this.arrA[Math.floor(this.arrA.length/2)].c:[@State](arkts-state.md#观察变化)无法观察到第二层的变化,但是ClassA被\@Observed装饰,ClassA的属性的变化将被\@ObjectLink观察到。 389 390 391### 二维数组 392 393使用\@Observed观察二维数组的变化。可以声明一个被\@Observed装饰的继承Array的子类。 394 395 396```ts 397@Observed 398class StringArray extends Array<String> { 399} 400``` 401 402使用new StringArray()来构造StringArray的实例,new运算符使得\@Observed生效,\@Observed观察到StringArray的属性变化。 403 404声明一个从Array扩展的类class StringArray extends Array<String> {},并创建StringArray的实例。\@Observed装饰的类需要使用new运算符来构建class实例。 405 406 407```ts 408@Observed 409class StringArray extends Array<String> { 410} 411 412@Component 413struct ItemPage { 414 @ObjectLink itemArr: StringArray; 415 416 build() { 417 Row() { 418 Text('ItemPage') 419 .width(100).height(100) 420 421 ForEach(this.itemArr, 422 (item: string | Resource) => { 423 Text(item) 424 .width(100).height(100) 425 }, 426 (item: string) => item 427 ) 428 } 429 } 430} 431 432@Entry 433@Component 434struct IndexPage { 435 @State arr: Array<StringArray> = [new StringArray(), new StringArray(), new StringArray()]; 436 437 build() { 438 Column() { 439 ItemPage({ itemArr: this.arr[0] }) 440 ItemPage({ itemArr: this.arr[1] }) 441 ItemPage({ itemArr: this.arr[2] }) 442 Divider() 443 444 445 ForEach(this.arr, 446 (itemArr: StringArray) => { 447 ItemPage({ itemArr: itemArr }) 448 }, 449 (itemArr: string) => itemArr[0] 450 ) 451 452 Divider() 453 454 Button('update') 455 .onClick(() => { 456 console.error('Update all items in arr'); 457 if ((this.arr[0] as Array<String>)[0] !== undefined) { 458 // 正常情况下需要有一个真实的ID来与ForEach一起使用,但此处没有 459 // 因此需要确保推送的字符串是唯一的。 460 this.arr[0].push(`${this.arr[0].slice(-1).pop()}${this.arr[0].slice(-1).pop()}`); 461 this.arr[1].push(`${this.arr[1].slice(-1).pop()}${this.arr[1].slice(-1).pop()}`); 462 this.arr[2].push(`${this.arr[2].slice(-1).pop()}${this.arr[2].slice(-1).pop()}`); 463 } else { 464 this.arr[0].push('Hello'); 465 this.arr[1].push('World'); 466 this.arr[2].push('!'); 467 } 468 }) 469 } 470 } 471} 472``` 473 474## ObjectLink支持联合类型 475 476@ObjectLink支持@Observed装饰类和undefined或null组成的联合类型,在下面的示例中,count类型为ClassA | ClassB | undefined,点击父组件Page2中的Button改变count的属性或者类型,Child中也会对应刷新。 477 478```ts 479class ClassA { 480 public a: number; 481 482 constructor(a: number) { 483 this.a = a; 484 } 485} 486 487class ClassB { 488 public b: number; 489 490 constructor(b: number) { 491 this.b = b; 492 } 493} 494 495@Entry 496@Component 497struct Page2 { 498 @State count: ClassA | ClassB | undefined = new ClassA(10) 499 500 build() { 501 Column() { 502 Child({ count: this.count }) 503 504 Button('change count property') 505 .onClick(() => { 506 // 判断count的类型,做属性的更新 507 if (this.count instanceof ClassA) { 508 this.count.a += 1 509 } else if (this.count instanceof ClassB) { 510 this.count.b += 1 511 } else { 512 console.info('count is undefined, cannot change property') 513 } 514 }) 515 516 Button('change count to ClassA') 517 .onClick(() => { 518 // 赋值为ClassA的实例 519 this.count = new ClassA(100) 520 }) 521 522 Button('change count to ClassB') 523 .onClick(() => { 524 // 赋值为ClassA的实例 525 this.count = new ClassB(100) 526 }) 527 528 Button('change count to undefined') 529 .onClick(() => { 530 // 赋值为undefined 531 this.count = undefined 532 }) 533 }.width('100%') 534 } 535} 536 537@Component 538struct Child { 539 @ObjectLink count: ClassA | ClassB | undefined 540 541 build() { 542 Column() { 543 Text(`count is instanceof ${this.count instanceof ClassA ? 'ClassA' : this.count instanceof ClassB ? 'ClassB' : 'undefined'}`) 544 .fontSize(30) 545 546 Text(`count's property is ${this.count instanceof ClassA ? this.count.a : this.count?.b}`).fontSize(15) 547 548 }.width('100%') 549 } 550} 551```