myTD
myTD

Reputation: 1469

Backbone - Limiting Number of Items to Show in a Collection

I have a dropdown box which will change number of items of a collection to be displayed on the page...

{{#each myCollection}}
<div id="{{this.Name}}">{{this.Name}} </div>
{/each}}
<select id="ddpFilter" >
<option value="10">Show 10</option>
<option value="50">Show 50</option>
</select>

Upvotes: 4

Views: 3938

Answers (1)

hurrymaplelad
hurrymaplelad

Reputation: 27785

Check out the first() Underscore method baked into Backbone Collections. Here's an example of how you might combine first() with your template:

Backbone.View.extend({

  // Number of items to show from the collection.  Set this and re-render when you 
  // want to show 50.
  limit: 10, 

  // Notice I switched myCollection to items.  Backbone collections aren't directly
  // iterable, but their underscore methods (like first(n)) return vanilla 
  // iterable Arrays
  template: Handlebars.compile("{{#each items}} {{this.Name}} {/each}}"),

  render: function() {
    this.$el.html(this.template({
      // Pass a truncated Array into the template to keep it logicless and Mustachy
      items: myCollection.first(this.limit)
    }));
  }
});

Upvotes: 4

Related Questions