首页 > 解决方案 > 在 Aurelia 中观察数组属性

问题描述

我的班级有一个财产:

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>

每当人们被添加到家庭中时,或者如果计算集合中的任何元素的任何渲染属性 , , 被更新,我firstName都需要更新列表。我怎样才能在 Aurelia 中做到这一点?如果我使用它不会检测到数组元素的变化,并且由于所有家庭中的人员列表是动态的,我不能只为每个元素创建一个观察者,而不创建一个系统来管理何时应该订阅/取消订阅观察者。lastNamephone@computedFrom()

标签: aurelia

解决方案


就在我即将放弃使用 Google 寻求解决方案的时候,Aurelia Signaling 来救援了。这段代码最终为我工作:

<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), []);
    }
}

推荐阅读