简体   繁体   中英

Polymer how to update filtered array

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?

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM