处理aurelia中的集合更新

Mat*_*ski 5 javascript aurelia

我正努力在Aurelia处理收藏更新的最佳方式.想象一下,我有一个视图(带有注释的新闻列表),它是使用以下模型中的一组repeat.fors构建的:

var news = [
    {
        id: 1,
        title: 'Some title',
        comments : ['comment1']
    },
    {
        id: 2,
        title: 'Some title',
        comments : ['comment1']
    },
    {
        id: 3,
        title: 'Some title',
        comments : ['comment1']
    }    
];
Run Code Online (Sandbox Code Playgroud)

我还使用setInterval()创建了计时器,它每秒都会获取新闻列表.现在想象下面的新闻列表会回来:

var freshNews = [
    {
        id: 1,
        title: 'Some title',
        comments : ['comment1', 'comment2']
    },
    {
        id: 2,
        title: 'Some title',
        comments : ['comment1']
    }
];
Run Code Online (Sandbox Code Playgroud)

如果我在我的重复中使用这个freshNews列表,因为它将重建整个DOM,显示导致闪烁的消息和用户输入的数据丢失(想象在每个新闻下面是textarea用于输入注释).

我如何处理这种情况?由于它的脏检查和ngRepeat工作方式(角度不会破坏对应于未更改的对象的DOM),这在Angular中工作得相当不错,在React中,由于shadow DOM,它也会很好用.

我如何在奥里利亚处理这种情况?

Ale*_*ran 6

问题实际上不是关于收藏品.这是一个普遍的JS问题. 如何在另一个对象中复制对象属性?

所以你可以很好地处理它.

您可以:

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
   }
}
Run Code Online (Sandbox Code Playgroud)

即使你将编辑器绑定到同一个对象 - 它也不会破坏用户注释.

freshNews.forEach(n=>{

    let update = news.find(o=>o.id==n.id)
    if (!update) {
        news.push(n)
    }
    else {
        Object.assign(update,n)
    }
})
Run Code Online (Sandbox Code Playgroud)