首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >观察Aurelia中的数组属性

观察Aurelia中的数组属性
EN

Stack Overflow用户
提问于 2018-10-11 23:26:20
回答 3查看 266关注 0票数 0

我的类中有一个属性:

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(),它将不会检测到数组元素的更改,而且由于所有家庭中的人员列表都是动态的,所以我不能只为每个元素创建一个观察者,而不创建一个系统来管理何时应该订阅/取消订阅观察者。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-10-12 17:02:44

使用脏检查

去掉@computedFrom(),你就会得到你想要的行为。

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

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

票数 1
EN

Stack Overflow用户

发布于 2018-10-12 00:21:40

就在我正要放弃在谷歌上寻找解决方案的时候,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
EN

Stack Overflow用户

发布于 2018-10-15 01:33:02

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52763763

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档