如何更新聚合物模型中的 hidden$= 属性?

How to update hidden$= attribute in a Polymer Model?

this jsbin 中,您应该能够在单击 'show more' 按钮时看到呈现的“4”。控制台将更改记录到 my-element 的模型,但 DOM 不更新。我做错了什么?

<!DOCTYPE html>
<html>
<head>
  <title>polymer</title>
  <script src="https://rawgit.com/webcomponents/webcomponentsjs/master/webcomponents-lite.js"></script>
  <link rel="import" href="https://rawgit.com/Polymer/polymer/master/polymer.html">
</head>
<body>

<dom-module id="my-element">
  <template>
    <button on-click="_dosomething">show more</button>
    <template is="dom-repeat" items="{{myItems}}" >
      <div hidden$="{{_isItemHidden(item, shownItems)}}">{{item}}</div>
    </template>
  </template>
</dom-module>

<script>
  HTMLImports.whenReady(function() {
    Polymer({
     is: 'my-element',
     ready: function() {
      this.myItems = [1,2,3,4,5];
      this.shownItems = [1,2,3]
     }, 
      _dosomething: function(){
        console.log(this.shownItems);
        this.push('shownItems', 4);
        console.log(this.shownItems);
      },
      _isItemHidden: function(item, shownItems) {
        return !shownItems.some(function (i) {return i == item});
      }
    });
  });
</script>

<my-element></my-element>


</body>
</html>

解决方案是 simple,要让系统收到通知并调用 _isItemHidden 函数,您必须更新 shownItems 数组的引用。

this.shownItems.push(4);

this.set('shownItems', this.shownItems.slice());

无需每次都创建一个新数组,您可以通过在计算绑定中使用通配符 * 来观察数组变化(从 here 中读取)。

因此您的绑定变为 -

<div hidden$="{{_isItemHidden(item, shownItems.*)}}">{{item}}</div>

你现在的计算函数应该是-

_isItemHidden: function(item, e) {
    return !e.base.some(function (i) { return i == item });
}

查看更新的 jsbin here