Polymer how to update filtered array

百般思念 提交于 2019-12-11 12:48:51

问题


I have a filtered dom-repeat array in Polymer like this:

<dom-module id="my-element">
  <template id="template" is="dom-repeat" items="[[rows]]" filter="filter">
    <span on-click="updateItem">[[item]]</span>
  </template>
</dom-module>
<script>
  Polymer({
    is: "my-element",
    ready: function() {
      this.rows = ['abc', 'def', 'ahi', 'jkl'];
    },
    filter: function(item) {
      return item.indexOf('a') > -1;
    },
    updateItem: function(event) {
      var index = this.$.template.indexForElement(event.target);
      this.set('rows.' + index, 'ghi');
    }
  });
</script>

The problem is in the function updateItem. Because the array is filtered, it will only shows ['abc', 'ahi']. When I click on the second span, or element 'ahi', updateItem is triggered. the method indexForElement will return index=1. However, in the rows array, ahi has index 2. Therefore, rows turn out to be ['abc', 'ghi', 'ahi', 'jkl'] instead of ['abc', 'def', 'ghi', 'jkl']

How do I update filtered array properly?


回答1:


Instead of getting the index from the filtered list, just get the actual item from it and do an indexOf from the original list.

var item = this.$.template.itemForElement(event.target);
var index = this.rows.indexOf(item);

this.set('rows.' + index, 'ghi');


来源:https://stackoverflow.com/questions/32150417/polymer-how-to-update-filtered-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!