jdepoix
jdepoix

Reputation: 485

Polymer: how to parse the index to the elements using template repeat

I've been trying to use Polymer for a project I'm working on. And although I enjoyed it quite a lot so far, I ran into a problem I just can't solve. I dumped it down to a simple example. Basically it's just a list element (item-list) that contains item elements (item-card) and i want to parse the items position to the element via the attribute pos. But for some reason the items attribute is allways undefined! Is this because the attribute is bound to the variable i, which dies after the template repeat? If so, how do I work around it? Is there a different approach I should be using here?

SOLUTION: You can find the solution by reading through all the comments, but to sum it up: apperantly there was a timing issue and the attribute wasn't ready at the ready callback. But I found out about the domReady callback (polymer lifecycle documentation). Using domReady it works just fine! Thanks to Günter Zöchbauer for the help!

This is the item-list.html:

<link rel="import" href="components/polymer/polymer.html">
<link rel="import" href="item-card.html">

<polymer-element name="item-list">
  <template>
    <style>
    </style>

    <template repeat="{{values, i in data.data}}">
      <item-card pos="{{i}}"></item-card>
    </template>

  </template>
  <script>
    Polymer({
      created: function()
      {
        this.num = 123456;

        this.data = { "data":
          [
            {
              "value":999
            },
            {
              "value":666
            },
            {
              "value":555
            },
            {
              "value":222
            }
          ]
        };
      }
    });
  </script>
</polymer-element>

This is the item-card.html

<link rel="import" href="components/polymer/polymer.html">

<polymer-element name="item-card" attributes="pos">
  <template>
    <style>
    </style>
  </template>
  <script>
    Polymer({
      ready: function()
      {
        console.log("ready: " + this.pos);
      }
    });
  </script>
</polymer-element>

I didn't bother putting the index.html in, since it just containts one item-list element.

Thanks alot!!

Upvotes: 1

Views: 772

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657476

I think you need a pos field in <item-card> in addition to the attributes="pos" declaration.

The repeated element also references the bound model which can be accessed like querySelector('item-card').templateInstance.model property.
See https://github.com/PolymerLabs/polymer-selector/blob/master/polymer-selector.html#L286 for an example.

Info:

According to the comments it turned out to be a timing issue. The value wasn't yet assigned when the ready callback was called but using domReady worked.

Upvotes: 1

Related Questions