Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer 1.0: How to stop dom-repeat loop from executing using a dom-if check inside the loop

Tags:

polymer-1.0

I am trying to accomplish a conditional binding using a dom-if inside a dom-repeat. Here is my code:

<template is="dom-repeat" items="{{customers}}">`
     <template is="dom-if" if="_continueLoop(index)" indexAs="index">
          Data renders here
     </template>
</template>

Function _continueLoop(index) looks like:

_continueLoop: function (value) {
      alert("This function is not being called at all!No alert message.");
      if (value == 1) return true;
      else return false;
}

My intention is to stop dom-repeat loop to continue if value of index is 1, i.e. when first 2 records are fetched I want the loop to stop fetching more.

What is the best way to do this?

like image 516
Subrata Sarkar Avatar asked Nov 29 '25 14:11

Subrata Sarkar


2 Answers

I don't think this is the best answer for the reason below, but I thought I would share one solution. You could use a filter:

<dom-module id="employee-list">
    <template>
      <template is="dom-repeat" items="{{employees}}" filter="_filter">
        <div># <span>{{index}}</span></div>
      </template>

    </template>

    <script>
      Polymer({
        is: 'employee-list',
        ready: function() {
          this.employees = [{
            name: 'Bob'
          }, {
            name: 'Sally'
          }];
        },
        _filter: function(item) {
          // This is slow. The larger your array, the worse
          // the performance will be 
          return this.employees.indexOf(item) < 1; 
        }
      });
    </script>
  </dom-module>

Note that this is not efficient, as the binding help pages explains:

Because of the way Polymer tracks arrays internally, the array index isn’t passed to the filter function. Looking up the array index for an item is an O(n) operation. Doing so in a filter function could have significant performance impact.

like image 57
MrK Avatar answered Dec 01 '25 06:12

MrK


Maybe you can make a filter before to pass data to dom-repeat. In this filter you will reduce the array elements as you need.
Another solution that may help you is modify the condition like this:

_notPassWhenValueIsGreaterThanOne: function (value) {
    return value <= 1;
}

If value<=1 the elements will be attached to dom, in other way this elements will be in memory, but elements will are not visible and dom-repeat´s iterates the entire array.

like image 40
Flavio Ochoa Avatar answered Dec 01 '25 06:12

Flavio Ochoa