Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with collection updates in aurelia

I'm struggling best way of dealing with collection updates in Aurelia. Imagine that I have a view (list of news with comments) which is built using set of repeat.fors from following model:

var news = [
    {
        id: 1,
        title: 'Some title',
        comments : ['comment1']
    },
    {
        id: 2,
        title: 'Some title',
        comments : ['comment1']
    },
    {
        id: 3,
        title: 'Some title',
        comments : ['comment1']
    }    
];

I also have timer created using setInterval(), which fetches list of news every second. Now imagine that following list of news comes back:

var freshNews = [
    {
        id: 1,
        title: 'Some title',
        comments : ['comment1', 'comment2']
    },
    {
        id: 2,
        title: 'Some title',
        comments : ['comment1']
    }
];

If I use this freshNews list in my repeat.for it will rebuild whole DOM that display news causing flicker and data entered by user being lost (imagine that under each news is textarea for entering comments).

How do I work on this scenario? This works quite nicely in Angular thanks to it's dirty checking and way ngRepeat works (angular will not destroy DOM corresponding to object that hasn't changed), in React it will also work nice thanks to shadow DOM.

How do I deal with this scenario in Aurelia?

like image 561
Mateusz Jamiołkowski Avatar asked Oct 16 '15 19:10

Mateusz Jamiołkowski


1 Answers

Question is not actually about collections. It is a general JS question. How to duplicate object properties in another object?

So you can actually deal with it pretty well.

You can:

iterate over your updates {
   find a relevant object in news
   if there is none { 
      just push the new one to collection
   }
   otherwise {
      apply new values to the old one
   }
}

even if you keep the editor tied to the same object - it won't destroy the users comment.

freshNews.forEach(n=>{

    let update = news.find(o=>o.id==n.id)
    if (!update) {
        news.push(n)
    }
    else {
        Object.assign(update,n)
    }
})
like image 65
Alexander Taran Avatar answered Sep 30 '22 15:09

Alexander Taran