Polymer 1.x: How to pre-process the items in a list or repeater?

83 views Asked by At

Here is the plunk.

Can anyone point me to a pattern that formats (or pre-processes) data items entering a repeater (like iron-list or iron-data-table) for example?

In other words, consider this plunk for example. Let's say I wanted to add a field to each user and display it in the list; let's call it namelength where:

item.user.namelength = item.user.name.first.length + item.user.name.last.length

How (where in the HTML or JS and using what pattern) would I best approach this pre-processing task?

content-el.html
<base href="https://polygit.org/polymer+:master/iron-data-table+Saulis+:master/components/">
<link rel="import" href="polymer/polymer.html">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>

<link rel="import" href="iron-ajax/iron-ajax.html">
<link rel="import" href="paper-button/paper-button.html">

<link rel="import" href="iron-data-table/iron-data-table.html">

<dom-module id="content-el">
    <template>
        <style></style>

    <iron-ajax
      auto
      url="https://saulis.github.io/iron-data-table/demo/users.json" 
      last-response="{{users}}">
    </iron-ajax>
    <iron-data-table items="[[users.results]]">
      <data-table-column name="Picture" width="50px" flex="0">
        <template>
          <img src="[[item.user.picture.thumbnail]]">
        </template>
      </data-table-column>
      <data-table-column name="First Name">
        <template>[[item.user.name.first]]</template>
      </data-table-column>
      <data-table-column name="Last Name">
        <template>[[item.user.name.last]]</template>
      </data-table-column>
      <data-table-column name="Email">
        <template>[[item.user.email]]</template>
      </data-table-column>
    </iron-data-table>

    </template>

  <script>
    (function() {
      'use strict';
      Polymer({
        is: 'content-el',
            });
        })();
  </script>
</dom-module>
2

There are 2 answers

0
LarsKnudsen On BEST ANSWER

E.g.

<data-table-column name="Name Length">
    <template>{{_len(item.user.name.first, item.user.name.last)}}</template>
</data-table-column>

...

(function() {
  'use strict';
  Polymer({
    is: 'content-el',
    _len: function(first, last) {
      return first.length + last.length;
    }
        });
    })();
0
tony19 On

You could use a computed binding that preprocesses user.results by adding the namelength field that you described:

// template
<iron-data-table items="[[_getUserData(users.results)]]">
  ...
  <data-table-column name="Name Length">
    <template>[[item.user.namelength]]</template>
  </data-table-column>
</iron-data-table>

// script
Polymer({
  is: 'content-el',
  _getUserData: function(items) {
    items.forEach(function(item) {
      var user = item.user;
      user.namelength = user.name.first.length + user.name.last.length;
    });
    return items;
  }
});

plunker