聚合物。模型更改后更新视图

时间:2016-09-22 12:48:33

标签: polymer

这是Polymer中关于更新模型时更新视图的常见问题(答案是使用this.set或this.push Polymer方法)。

但是当我有两个元素时:

第一个要素:

properties:{
  items: {
    type: Array
  }
},

someFunction: {
  this.push('items', {'Name': 'something'});
}

第二个元素具有与第一个元素

中的“项目”绑定的属性
ready: function(){
    this.items = firstElement.items;
}

我希望在firstElement上更新'items'时更新第二个元素'items'。由于应用限制,我无法手动通知secondElement。

所以现在我看到(在devTools中)第二个元素的模型是正确的('items'包含对象),但是视图没有更新。

如何更新?

2 个答案:

答案 0 :(得分:0)

您需要在第一个元素的属性上设置notity以接收元素本身之外的更改

properties:{
  items: {
    type: Array,
    notify: true
  }
},

然后,在secondElement中你可以

<firstElement items="{{items}}" />

答案 1 :(得分:0)

让Polymer two-way binding为您处理通知。

在容器元素x-foo中考虑两个元素x-barx-app

  1. x-foo中,使用items声明notify:true,以便其更改将向上传播。

    Polymer({
      is: 'x-foo',
      properties: {
        items: {
          type: Array,
          value: function() { return []; },
          notify: true
        }
      }
    });
    
  2. x-app中,将x-foo的{​​{1}}绑定到items

    x-bar

    现在,<dom-module id="x-app"> <template> <x-foo items="{{items}}"></x-foo> <x-bar items="[[items]]"></x-bar> </template> <script> Polymer({ is: 'x-app' }); </script> </dom-module> 会通知x-bar数组的所有更改(添加/删除项目时)。

  3. items
    HTMLImports.whenReady(() => {
      "use strict";
    
      Polymer({
        is: 'x-app'
      });
      
      Polymer({
        is: 'x-foo',
        properties: {
          items: {
            type: Array,
            value: function() { return []; },
            notify: true
          }
        },
    
        _addItem: function() {
          this.push('items', {name: 'item' + this.items.length});
        }
      });
      
      Polymer({
        is: 'x-bar',
        properties: {
          items: {
            type: Array
          }
        }
      });
    });

    codepen

相关问题