简体   繁体   中英

Completely reset a dom-repeat element with new data

Every once in a while, <dom-repeat> 's penchant for trying to be smarter than it needs to be causes problems with property binding, resulting in recycled elements displaying stale or duplicate data.

Regardless of how much this.splice() ing or this.push() ing you try it seems to do little more than waste cycles as it has zero effect.

At this point doing whatever the documentation tells you to do--which amounts to trying to figure out the correct combination of arcane bindings to subproperties and subarrays, and observer-triggering mutators to get the black magic to work--seems like a waste of effort, and it would be faster and easier to wipe the slate and rebuild the elements from a fresh state. So how can this be accomplished?

Despite the prior lack of answers in this subject, it turns out that resetting a <dom-repeat> is pretty easy. Simply wrap the <dom-repeat> in a <dom-if> which binds to a reset property, which can be freely used to kill and reconstruct the <dom-repeat> as necessary.

First, we define the data which needs to be reset.

<iron-ajax id="retrieveData"
           method="get"
           url="/api/data"
           handle-as="json"
           on-response="_handleData">
</iron-ajax>
<template is="dom-if" if="[[!_reset]]">
  <template is="dom-repeat" items="[[veryComplicatedObjects]]">
    <my-complicated-custom-element content={{item}} on-change="_remoteChanged"/>
  </template>
</template>

And now we write our event handlers

_remoteChanged() {
  // trigger retrieval of new data
  this.$.retrieveData.generateRequest()
}

_handleData(e) {
  // kill dom-repeat
  this.setProperties({
    veryComplicatedObjects: []
  })
  this._reset = true

  // reconstruct dom-repeat
  this.setProperties({
    veryComplicatedObjects: e.detail.response
  })
  this._reset = false
}

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