2014-05-14 50 views
1

我正在使用if-模板來顯示或隱藏聚合物元素內的列表中的項目。 我的模板基於一系列值,並使用參考列表進行過濾。聚合物if-帶過濾器的模板:過濾器沒有更新

更新值列表會產生所需的效果。但是,更改過濾器引用列表(此處刪除一個元素)不會產生模板的更新。

<!DOCTYPE html> 
<html> 
<head> 
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.2.3/platform.js"></script> 
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.2.3/polymer.js"></script> 
    <meta charset="utf-8"> 
    <title>JS Bin</title> 
</head> 
<body> 
    <test-component></test-component> 
</body> 
</html> 

<polymer-element name='test-component' attributes='itemlist filterlist'> 
    <template> 
    <style> 
    </style> 
    <table id='table'> 
     <tr template repeat="{{item in itemlist}}"> 
     <template if="{{item | applyFilter(filterlist)}}"> 
      <td>test</td> 
     </template> 
     </tr> 
    </table> 
    <input type='button' value='remove 1 element' on-click={{clicked}}></input> 
    <div id='msg'></div> 
    </template> 
    <script> 
    Polymer('test-component', { 
     itemlist: [1,2,3], 
     filterlist: [1,2], 
     applyFilter: function(item, filterlist) { 
     var test = false; 
     if (filterlist) { 
      filterlist.forEach(function(filteritem) { 
      test = test || ((new RegExp(filteritem)).test(item)); 
      }); 
     } 
     return test; 
     }, 
    clicked: function() { 
    this.$.msg.innerHTML = 'Filter list was ' + this.filterlist; 
    this.filterlist.splice(1,1); 
    this.$.msg.innerHTML += ', now it\'s ' + this.filterlist; 
    } 
}); 

可運行的代碼見http://jsbin.com/vuvikare/4/edit?html,output

有沒有辦法觸發此更新(例如使用filterChanged觀察者)?

感謝

回答

1

這不能不說是一個黑客,但加入這個方法我got it to work

filterlistChanged: function() { 
    Array.prototype.forEach.call(this.$.table.querySelectorAll('template[if]'), function(t) { 
    t.iterator_.updateIteratedValue(); 
    }); 
}, 

基本上,發現表中的所有內模板元素,並強制其進行更新(使用一個私人方法)。

+0

你也可以簡化你的標記,這將刪除filterListChanged中循環的需要:http://jsbin.com/vuvikare/12/edit?html,output – CletusW

+1

現在我記得我爲什麼總是印象深刻由黑客... 非常感謝 –