2015-10-16 34 views
5

我正在努力處理Aurelia中收集更新的最佳方式。想象一下,我有一個觀點(與評論新聞列表),這是使用repeat.fors的一套建從以下模型:處理aurelia中的收集更新

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

我也有使用的setInterval(),它獲取的新聞列表每一秒定時器產生。現在想象一下,下面的新聞列表回來:

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

如果我用我的repeat.for這個freshNews列表它會重建整個DOM是顯示的消息引起的閃爍和由用戶輸入的數據丟失(想象下的每個新聞是textarea輸入評論)。

我該如何處理這種情況?這在Angular中工作得非常好,這要感謝它的髒檢查和ngRepeat工作方式(角度不會毀壞與沒有改變的對象相對應的DOM),在React中它也可以很好地工作,這要歸功於陰影DOM。

我該如何處理Aurelia中的這種情況?

+0

只是一個評論,我相信你的意思是「虛擬」DOM的React,而不是ShadowDOM。 –

+0

是的,你是對的 –

+0

你解決了這個問題嗎?去年我有類似的問題,但沒有得到滿意的解決方案。 –

回答

2

問題實際上並不涉及收藏。這是一個普通的JS問題。 How to duplicate object properties in another object?

所以你實際上可以很好地處理它。

您可以:

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

即使您保持連接到相同的對象編輯器 - 它不會破壞用戶評論。

freshNews.forEach(n=>{ 

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