[英]Polymer change in an element in a dom-repeat not reflected on parent array
[英]Updating array in items of template dom-repeat not reflected to dom
考慮以下代碼:
<template is="dom-repeat" items="{{chats}}" as="item">
<p>{{item.name}}</p>
<span>{{item.unreadcount}}</span>
</template>
我似乎無法確保替換數組(完全,不只是更新元素之一的屬性)更新dom。
更新我嘗試這樣的:
var c = this.chats;
c.forEach(function(e) {
e.unreadcount = Math.floor(Math.random() * 10) + 1;
}.bind(this));
// none of the following approaches has any effect:
this.chats = c;
this.set("chats", c);
this.notifyPath("chats", c);
如果陣列已完全更改,如何實現重新渲染dom?
編輯
多虧了Maria的提示,我才知道該怎么做。
使用splice()
是不夠的,還需要使用Polymer的函數來修改數組本身: this.set(..., ...)
。
for (i = 0; i < this.chats.length; i++) {
this.set('chats.'+i+'.unreadcount', Math.floor(Math.random() * 10) + 1);
}
this.chats = this.chats.slice();
自從開始使用Polymer以來,由於我的頭撞在牆上,我的前額開始變得扁平
這里的問題是,在完成所有這些操作之后,您的chats
屬性仍然是數組的同一實例。 在您嘗試的任何方法中,Polymer都會檢查實例是否已更改,但不會檢查陣列中的項目是否發生更改。 解決此問題的一種方法是創建數組的新副本,並將其分配給chats
。
this.chats = c.slice();
更新資料
盡管我可以肯定以上內容在某些時候可以使用,但我可以確認它不再可用。 我認為Polymer具有某種緩存的舊值。 因此,我認為您使用set
API的解決方案是最好的選擇。 我發現以下方法也可以使用,但我猜想它在大多數情況下效率較低。 它將重置數組,然后異步設置新值。 在這種情況下,甚至不需要切片。
this.chats = [];
this.async(function() {
this.set("chats", c);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.