属性 对对象属性的依赖

Property dependencies on object attributes

我想使用 属性 依赖项来避免对计算属性进行脏检查。由于计算 属性 所依赖的属性不是基元而是对象的属性,因此我不知道如何进行这项工作。

代码:

import {computedFrom} from 'aurelia-framework';

export class Person {
    personData = {
        firstName: 'John',
        lastName: 'Doe',
        // More attributes...
    }

    // ...

    // Doesn't work:
    @computedFrom('personData.firstName', 'personData.lastName')
    // Neither does:
    // @computedFrom('personData["firstName"], 'personData["lastName"]')
    // Nor:
    // @computedFrom('personData')
    get fullName() {
        return `${this.personData.firstName} ${this.personData.lastName}`;
    }

    // ...
}

我会在 personData 属性上添加观察者 () 并手动设置 fullName

使用@computedFrom('personData') 并始终在属性更改时创建新的personData this.personData = Object.assign({}, this.personData, {firstName: "new first name"})

@computedFrom属性即将添加对表达式的支持-关注https://github.com/aurelia/binding/pull/276

提醒一句 - 过度使用 @computedFrom(例如 @computedFrom(p1.p2.p3, p4.p5, p6, p7, p8))最终可能会比 dirty-checking 性能更差。 one-time 观察者设置与 dirty-checking 连续函数评估之间存在权衡 - 你的里程可能会有所不同。

另一种选择是在您的视图中使用 with 绑定并直接绑定到您的对象道具:

<span with="personData">${firstName} ${lastName}</span>

最后但同样重要的是,aurelia-computed 插件可以解析 getter 函数体并生成不使用 dirty-checking 的观察者:https://github.com/jdanyow/aurelia-computed