【问题标题】:Mutating object properties within an array with Polymer使用 Polymer 改变数组中的对象属性
【发布时间】:2016-10-30 22:10:57
【问题描述】:

我不确定如何解决这个问题。我相信很快就会有人知道这一点。

我有一个对象数组并修改了一个属性。我有一个 Firebase 监听器“child_changed”。更新firebase时需要更新数组。这是下面的代码。

     dbRefList.on('child_changed', function(snap) {
          
          var len = this.grocerylist.length;
          for(var i=len; i--;) {
   
            if(this.grocerylist[i].key === snap.key) {
              this.set(['grocerylist', i, 'selected'], snap.val().selected);
            }
          }
        
          this.notifyPath('grocerylist', this.grocerylist.slice());

        }.bind(this));

当数组被修改时,我希望模板 repeat-dom 触发。我知道 this.set 不会触发数组突变子属性,但我再次不确定如何解决这个问题。我做了研究并尝试了很多解决方案。

我可以在模板 dom-repeat 上强制渲染,但我更喜欢数据绑定方式。

【问题讨论】:

    标签: arrays polymer


    【解决方案1】:

    所以这段代码(只是你现在在那里的this.set)应该导致grocerylist.i.selected 的值在dom-repeat 内更新(假设它被绑定在那里,所以它实际上会显示出来)。

    你看到了什么行为?您是否尝试根据 selected 值对列表进行过滤或排序?在这种情况下,您可能需要在dom-repeat 上添加observe="selected"

    (另外,您是否确认 child-changed 回调是使用您期望的 this 值(元素)而不是 window 或其他东西调用的?)

    您应该能够通过执行this.grocerylist = this.grocerylist.slice()this.set('grocerylist', this.grocerylist.slice()); 来强制刷新...notifyPath 在这里不起作用,因为notifyPath 不会更改值,它会通知元素有关先前的更改(第二个参数实际上被忽略了)。

    【讨论】:

    • 它确实用我设置的新选定值更新了 this.grocerylist,也许我可以尝试 observe="selected"。我试过 this.grocerylist = this.grocerylist.slice() 不起作用。感谢observe="selected" 提示
    • 那么如果新值出现了,有什么问题呢?查看更多代码会很有帮助(例如您的 dom-repeat 和任何过滤器或排序方法)。
    猜你喜欢
    • 1970-01-01
    • 2017-05-19
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多