编程语言
首页 > 编程语言> > javascript – Polymer.prototype.splice的行为不符合预期

javascript – Polymer.prototype.splice的行为不符合预期

作者:互联网

我正在使用Polymer的阵列变异方法进行数组突变.

  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

解决方法:

实际上应该从数组中删除该项.第二次注销为[splices:Object]只是为了显示有关此数组的更多信息,因为它有一个名为splices的属性.如果你在Firefox中运行相同的东西,你仍然会看到[object]所以我想这只是一个Chrome控制台助手的事情.

要获取要更新的值,一种方法是将this.push调用包装在this.async方法中.

  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的工作样本.

标签:javascript,polymer
来源: https://codeday.me/bug/20191008/1873861.html