Search code examples
polymer

Polymer iron-list dynamically adding items?


I'm trying to migrate some code from Polymer 0.5 to 1.x, this means moving from core-list to iron-list. However, I can not figure out an iron equivalent to how I was adding items to the core-list.

<core-list height="85">
<template>
<div class="{{ {selected: selected} | tokenList }}" style="padding:5px;"><paper-fab mini icon="arrow-forward" title="arrow-forward"></paper-fab> <!--{{index}}-->{{model.name}}</div>
</template>
</core-list>

which is called updated via...

document.querySelector('core-list').data = $.parseJSON('[{"name":"One"},{"name":"Two"}]');

Anyone have any suggestions?


Update : Jul-23-2015 12:20PM PST @Zikes

Following the suggestion posted, I have the following.

<dom-module id="my-element">
  <template>
    <iron-list items="[[myItems]]" as="item">
      <template>
        <div>[[item.name]]</div>
      </template>
    </iron-list>
  </template>
  <script>
    Polymer({
      is:'my-element',
      properties: {
        myItems: Array
      },
      addItem: function(item) {
        this.push('myItems', {name: item});
      }
    });
  </script>
</dom-module>

If this is setup right, how would I go about calling the addItem method from elsewhere?


Update : Jul-23-2015 1:58PM PST @Zikes

Following is my current code. While I can manipulate the array, values added to it in the ready or addItem method are not being displayed.

<dom-module id="fnord-element">
  <template>
    <iron-list items="[[myItems]]" as="item">
      <template>
        <div class="item">[[item.name]]</div>
      </template>
    </iron-list>
  </template>
  <script>
    Polymer({
      is:'fnord-element',
      properties: {
        myItems: {
            type: Array,
            notify: true
        }
      },
      addItem: function(item) {
        //this.push("myItems", {"name":item});
        this.myItems=[{name:item}];
        alert(this.myItems[0].name);
        //alert(item);
      },
      ready: function() {
        //alert('fnord');
        this.myItems=[{name:"One"},{name:"Two"}];
      }
    });
  </script>
</dom-module>
<fnord-element id="fnord"></fnord-element>
<paper-button raised onclick="document.querySelector('#fnord').addItem('John Doe');">Test</paper-button>

Solution

  • iron-list uses the items property to generate its items, similar to dom-repeat. What you can do is simply bind it to an Array in your component, like so:

    <dom-module id="my-element>
      <template>
        <iron-list items="[[myItems]]">
          <template>
            <div>[[item]]</div>
          </template>
        </iron-list>
      </template>
      <script>
        Polymer({
          is:'my-element',
          properties: {
            myItems: Array
          }
        });
      </script>
    </dom-module>
    

    Then, just follow the rules for modifying an Array property and you're all set!