Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update list in Aurelia using EventAggregator

I am using app-contacts demo to learn Aurelia, yes I know, it's incomplete as mentioned by @Eisenberg, but then I thought to use EventAggregator to notify the app.js, when I save the contact or create a new contact. Till now everything works fine. I am able to receive the contact object in app.js, but now I would like to update the contact list, which is not working and when I save a contact and update the contacts list in app.js, it gets removed.

Code added in app.js and subscribe method is called in constructor.

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);
        }
    });
}

No changes made to 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>

How to update the list?

Update This worked for me, but not sure what is the right approach

subscribe(){    
  this.ea.subscribe('contact_event', payload => {
    return this.api.getContactList().then(contacts => {
      this.contacts = contacts;
    });
  });
}
like image 360
Kishore Kumar Avatar asked Nov 10 '22 18:11

Kishore Kumar


1 Answers

Eric L. Anderson does a great job of explaining how this works in his blog post: Aurelia's Event Aggregator. It's event the same type of code you're trying to do!

Note: it's probably far too late to answer Kishore's question, but I'm putting the link in for others who end up here from a search.

like image 171
AR. Avatar answered Nov 14 '22 21:11

AR.