问题
I'm doing array mutation with Polymer's array mutation methods.
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);
And the annoying thing is this. When I bind this.allRules into a dom-repeat template, such as the one below, when updated binded data, it shows the item that was spliced instead of the newly added item. So after a splice and a push, instead of getting "abcdxfdsa" as item name, I get abc, which is the value before splicing. Here is the link to a sample dom-repeat data binding. Polymer dom-repeat how to notify array updated
回答1:
Actually the item should be removed from the array. The second time it logs out as [splices: Object] just to show more info about this array, as it has a property called splices. If you run the same thing in Firefox you will still see [object] so I guess this is just a Chrome console helper thing.
To get the value to be updated, one way is to wrap the this.push call inside a this.async method.
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);
});
Have a look at this plunker for a working sample.
来源:https://stackoverflow.com/questions/32082760/polymer-prototype-splice-dont-behave-as-expected