观察Aurelia中的阵列属性

时间:2018-10-11 15:26:20

标签: aurelia aurelia-binding

我在课堂上有一个财产:

class Control {
    @bindable households;

    get people() {
        return households
            .map(household => househould.people)
            .reduce((g1, g2) => g1.concat(g2), []);
    }
}

我用来计算所有住户中所有people[]的集合,然后将其呈现在此处:

<ul>
    <li repeat.for="person of people">
        ${person.firstName} ${person.lastName} - ${person.phone}
    </li>
</ul>

无论何时有人添加到家庭中,或者计算的集合中的任何元素的firstNamelastNamephone的任何呈现的属性,我都需要更新列表已更新。如何在Aurelia中做到这一点?如果我使用@computedFrom(),它将无法检测到数组元素的变化,并且由于所有家庭中的人员列表都是动态的,因此我不能仅为每个元素创建一个观察者,而无需创建一个管理何时应该观察者的系统。已订阅/未订阅。

3 个答案:

答案 0 :(得分:1)

我即将放弃能够向Google寻求解决方案的权利,Aurelia Signaling came to the rescue。这段代码最终为我工作:

<ul>
    <li repeat.for="person of people">
        <!-- May work without this rendering method,
            this is just closer to what my actual code is doing. -->
        ${renderPersonInfo(person) & signal: 'example-signal'}
    </li>
</ul>

和班级

import {BindingSignaler} from 'aurelia-templating-resources';

@inject(BindingSignaler)
class Control {
    @bindable households;

    constructor(bindingSignaler) {
        this.bindingSignaler = bindingSignaler;
        //Obviously, you can have this trigger off any event
        setInterval(() => this.bindingSignaler.signal('example-signal'), 1000);
    }

    get people() {
        return households
            .map(household => househould.people)
            .reduce((g1, g2) => g1.concat(g2), []);
    }
}

答案 1 :(得分:1)

使用脏物检查

离开export class App { @bindable households; get people() { const households = this.households || []; // Make sure househoulds is defined. return households.reduce((people, household) => people.concat(household.people), []); } } ,您将实现所需的行为。

react-native-device-info

https://gist.run/?id=040775f06aba5e955afd362ee60863aa

答案 2 :(得分:0)

您必须尽可能避免使用dirty-checking,信号是您的方案的理想选择。请记住,如果要在数组上使用computedFrom,可以通过查看其length属性而不是dirtyChecking来实现,就像下面的@computedFrom("myArray.length")