Work with collection updates in Aurelia

I'm struggling to cope with the collection updates at Aurelia. Imagine that I have a view (news list with comments) that is built using the repeat.fors set from the 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 a timer created using setInterval (), which retrieves a news list every second. Now imagine that the following list of news returns:

 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 replay., It will rebuild the entire DOM, displaying news, causing flicker and user input that is lost (imagine that there is a text area under each newsletter to enter comments).

How can I work on this scenario? This works well in Angular thanks to the dirty validation and ngRepeat way of working (angular will not destroy the DOM corresponding to an object that has not changed), in React it will also work well thanks to the shadow DOM.

How can I handle this scenario in Aurelia?

+5
source share
1 answer

The issue is not really about collections. This is a general JS question. How to duplicate properties of an object in another object?

So you can handle this 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 bind the editor to the same object, it will not destroy user comments.

 freshNews.forEach(n=>{ let update = news.find(o=>o.id==n.id) if (!update) { news.push(n) } else { Object.assign(update,n) } }) 
+4
source

Source: https://habr.com/ru/post/1233891/


All Articles