Week 22 | Filter and Sorting

polymer 1.0
Mon Jan 23 2017

The template repeater has two more interesting attributes for filtering and sorting.

The sort attribute will sort the items according the comparer function sortPriority. In the sort priority we can see that we compare two items concerning their priority subproperties and this will sort the items according to priority in ascending order. To learn more on sort function you can checkout the w3c page at the following link => http://www.w3schools.com/jsref/jsref_sort.asp .

Lastly, in the filter attribute we’ll run the computeFilter every time the filterString changes. This function will return true if the text of the message each time has a substring of the string entered.

<!DOCTYPE html>
<html>
<head>
  <script src="https://polygit.org/polymer+:1.3.1/components/webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="https://polygit.org/polymer+:1.3.1/components/polymer/polymer.html" />
</head>
<body>
  <alert-element></alert-element>
  <dom-module id="alert-element">
    <template>
      <input value="{{filterString::input}}">
      <br/>
      <template is="dom-repeat" items="{{messages}}" as="message" 
      filter="{{computeFilter(filterString)}}" sort="sortPriority">
        {{message.text}}: {{message.priority}}
        <br/>
      </template>
    </template>
  </dom-module>
  <script>
    HTMLImports.whenReady(function() {
      Polymer({
        is: "alert-element",
        properties: {
          messages: {
            type: Array,
            value: function() {
              return [{
                text: 'One Message',
                priority: 2
              }, {
                text: 'Another Message',
                priority: 5
              }, {
                text: 'Message',
                priority: 4
              }, {
                text: 'Best Message',
                priority: 3
              }, {
                text: 'Message 4',
                priority: 1
              }, {
                text: 'Message 5',
                priority: 4
              }, ];
            }
          },
          filterString: {
            type: String
          }
        },
        sortPriority: function(a, b) {
          return a.priority - b.priority;
        },
        computeFilter: function(text) {
          return function(message) {
            return message.text.indexOf(text) > -1;
          }
        },
        ready: function() {
          //this.set('messages.2.priority', 'Major');
        }
      });
    });
  </script>
</body>
</html>

Full Stack Weekly Newsletter

A free weekly newsletter for full stack web developers!