P.C
P.C

Reputation: 65

Polymer nested dom-repeat

I'm having some trouble with Polymer's <dom-repeat>.

I have parent objects (folders) and child objects (content of the folders). Both are computed from responses to an AJAX request.

The result should be something like:

Folder

  • child
  • child
  • child

My code:

<iron-ajax id="folder" url="../Folder" auto last-response="{{folders}}"></iron-ajax>

<template is="dom-repeat" items="{{folders.items}}" as="folder">
  <paper-card  on-tap="openFolder" object item="[[folder]]">

    <custom-object value="[[folder]]" link></custom-object>
     
    <iron-ajax id="folder" url="..[[folder.id]]/children" auto last-response="{{children}}"></iron-ajax>

    <template is="dom-repeat" items="{{children.items}}" as="children"> 
      <custom-object style="margin-top: 15px" value="[[children]]" link></custom-object>
    </template>

  </paper-card>
</template>

The issue is every folder becomes the child of the last folder and not his own.

Upvotes: 4

Views: 1437

Answers (1)

tony19
tony19

Reputation: 138196

Your inner iron-ajax writes to the same children property in each iteration of the repeater. The repeater does not scope that property, and it's actually visible to each iteration and to the entire template outside the repeater. It's likely that subsequent iterations are overwriting the children of the previous iteration, which manifests as unexpected nesting of folders.

One way to address this is to scope the children property to each iteration by attaching it to the iterator (i.e., folder in this case). To avoid a potential name collision with an actual property, it would be a good idea to prefix it (e.g., folder._children), as seen in this example:

<iron-ajax id="folder" url="../Folder" auto last-response="{{folders}}"></iron-ajax>

<template is="dom-repeat" items="{{folders.items}}" as="folder">
  <paper-card  on-tap="openFolder" object item="[[folder]]">

    <custom-object value="[[folder]]" link></custom-object>


    <!--
        attach a new property `_children` to `folder` to contain the response for this folder
    -->
    <iron-ajax url="..[[folder.id]]/children" auto last-response="{{folder._children}}"></iron-ajax>


    <template is="dom-repeat" items="{{folder._children.items}}" as="children"> 
      <custom-object style="margin-top: 15px" value="[[children]]" link></custom-object>
    </template>
  </paper-card>
</template>

Upvotes: 3

Related Questions