使用EventAggregator更新Aurelia中的列表

Update list in Aurelia using EventAggregator

本文关键字:列表 Aurelia EventAggregator 更新 使用      更新时间:2024-07-03

我正在使用应用程序联系人演示来学习Aurelia,是的,我知道,正如@Eisenberg所说,它是不完整的,但后来我想在保存联系人或创建新联系人时使用EventAggregator来通知app.js。到目前为止一切都很好。我可以在app.js中接收联系人对象,但现在我想更新联系人列表,但它不起作用,当我在app.jss中保存联系人并更新联系人列表时,它会被删除。

在app.js和subscribe方法中添加的代码在构造函数中调用。

subscribe(){
    this.ea.subscribe('contact_event', payload => {
        console.log(payload);
        var instance = JSON.parse(JSON.stringify(payload));
        let found = this.contacts.filter(x => x.id == payload.id)[0];
        if(found){
            let index = this.contacts.indexOf(found);
            this.contacts[index] = instance;
        }else{
            instance.id = this.contacts.length + 1;
            this.contacts.push(instance);
        }
    });
}

app.html 没有更改

<li repeat.for="contact of contacts" class="list-group-item ${contact.id === $parent.selectedId ? 'active' : ''}">
  <a href="#" click.delegate="$parent.select(contact)">
    <h4 class="list-group-item-heading">${contact.firstName} ${contact.lastName}</h4>
    <p class="list-group-item-text">${contact.email}</p>
  </a>
</li>

如何更新列表?

更新这对我有效,但不确定什么是正确的方法

subscribe(){    
  this.ea.subscribe('contact_event', payload => {
    return this.api.getContactList().then(contacts => {
      this.contacts = contacts;
    });
  });
}

Eric L.Anderson在他的博客文章中很好地解释了这是如何工作的:Aurelia的事件聚合器。这是一个与您尝试执行的代码类型相同的事件!

注意:现在回答Kishore的问题可能为时已晚,但我会为其他搜索到这里的人添加链接。