2015-08-18 149 views
2

我正在做陣列突變聚合物的陣列突變方法。Polymer.prototype.splice行爲不如預期

this.allRules = [{name: "abc", enabled: true}];  

    var item = this.allRules[index]; 
    item.name = "abcdxfdsa"; 
    item.enabled = enabled; 

    // console log out [Object] 
    console.log(this.allRules); 
    this.splice('allRules', index, 1); 
    // Instead of logging out [], it logs out [splices: Object] 
    console.log(this.allRules); 
    this.push('allRules', item); 
    // It logs out [Object, splices: Object] 
    console.log(poly.allRules); 

而令人討厭的是這個。當我將this.allRules綁定到dom-repeat模板(如下面的模板)中時,當更新的綁定數據時,它顯示拼接的項目而不是新添加的項目。所以在拼接和推送之後,我沒有得到"abcdxfdsa"作爲項目名稱,而是獲得了abc,這是拼接前的值。這裏是一個示例dom-repeat數據綁定的鏈接。 Polymer dom-repeat how to notify array updated

回答

3

實際上該項目應該從數組中刪除。第二次註銷爲[splices: Object]只是爲了顯示有關此數組的更多信息,因爲它有一個名爲splices的屬性。如果你在Firefox中運行同樣的東西,你仍然會看到[object],所以我想這只是Chrome控制檯的幫手。

來獲取值進行更新,一種方式是包裝一個this.async方法裏面this.push電話。

this.async(function() { 
    this.push('allRules', item); 
    console.log(item); 
    console.log(this.allRules[0].name); 
    // returns 1, meaning it's filled with one item again 
    console.log(this.allRules.length); 
    }); 

看看這個plunker爲工作示例。

+0

我遇到了另一個煩人的問題,這次是用過濾數組。我真的很感激你的時間請看看http://stackoverflow.com/questions/32150417/polymer-how-to-update-filtered-array –

+2

這是我花了幾個小時尋找的解決方案。如果數組的長度實際發生變化,Polymer.splice只會更新模板dom-repeat。如果您刪除某些內容並添加其他內容,則其長度不變,因此不會更改;你需要使用異步,所以長度先縮短然後再延長 –

+1

上面@DavidChu的評論與答案本身一樣珍貴。 – montrealist