骨干 - 限制集合中显示的项目数

时间:2012-10-17 06:34:56

标签: collections backbone.js limit mustache

我有一个下拉框,它会更改要在页面上显示的集合的项目数...

{{#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>

1 个答案:

答案 0 :(得分:4)

查看first()下划线方法baked into Backbone Collections。以下是您可以将first()与模板结合使用的示例:

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)
    }));
  }
});