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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With