Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Polymer Repeat value in range 1...n

I've started messing with Polymer and I've done the basic tutorial with the social media cards. In it several cards care looped over as repeat="{{post in posts}}". What I would like to do is something like repeat="{{post in range 1...10}}". Ultimately I'd like to use a published property cols to provide a max value instead of 10. I've been able to get something like this working by setting the cols property to something like [1,2,...,9] but that is unreasonable to any large set of values. I've also expanded on this by using the ready function and executing this.colsAr = new Array(cols), then in the repeat `{{col in colsAr}}.

What is the best/correct method of looping over a variable number of elements where the number is determined by a property?

To add to this lets also say the cols property is dynamically changed via a select input. This should cause a re-draw when a new value is selected.

like image 964
RogerSmith Avatar asked Jan 31 '26 17:01

RogerSmith


1 Answers

Generally the best way to do this is to use a computed property to express your filtered Array.

Something like this:

 <template repeat="{{post in slice}}">
   ...
  computed: {
    slice: 'sliced(posts)'
  },
  sliced: function(posts) {
    return posts.slice(1, 3);
  }

However, right now, the computed property engine doesn't automatically ArrayObserve posts, so we have to manually force a re-compute when the Array structure changes.

  kick: 0,
  computed: {
    slice: 'sliced(posts, kick)'
  },
  sliced: function(posts) {
    return posts.slice(1, 3);
  },
  postsChanged: function() {
    this.kick++;
  }

Incrementing kick forces the data engine to recompute slice (gives it a kick). Fwiw, we are trying to improve this particular situation, but the above technique should work in the short term.

Working example:

http://jsbin.com/dadeto/3/edit

like image 78
Scott Miles Avatar answered Feb 03 '26 07:02

Scott Miles