Ziyad Parekh
Ziyad Parekh

Reputation: 3

How would you render the first n models from a collection?

I have a parent view that fetches a collection of 20 models from the server. The parent view then calls on three subviews to render. Each of these child views uses the collection but all to a different degree. For instance, one will use all the models, while the other two will only need the first 5 models to render initially. I would like to pass a collection of the first five models to the two childviews that only need five, and pass the full collection to the view that uses all of them.

I could render them all separately and make three different calls to the server, but 1 call is better than 3 and I was wondering if there is a way to do this with only call.

I've tried the underscore method _.first(this.collection.models, 5) but when you pass this result to the view as :

this.view = new View({collection:_.first(this.collection.models, 5) }) I get an error

Any help would be appreciated.

Thanks

Upvotes: 0

Views: 33

Answers (1)

Dmytro Yarmak
Dmytro Yarmak

Reputation: 1018

You can use method collection.first but this method returns array of models. So you need to create new Collection from it:

var firstFive = new Backbone.Collection(fullCollection.first(5));

Upvotes: 1

Related Questions