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?
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)
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With