我正在使用 app-contacts 演示来学习 Aurelia,是的,我知道,正如@Eisenberg 所提到的那样,它是不完整的,但是当我保存联系人或创建新联系人时,我想使用 EventAggregator 来通知 app.js。到目前为止,一切正常。我能够在 app.js 中接收联系人对象,但现在我想更新联系人列表,但它不起作用,当我保存联系人并更新 app.js 中的联系人列表时,它会被删除。
在 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;
});
});
}