Question

my Collection fetches a few records and I have to show only top 10 records from it. I attempted

   this.collection.each(function(){
        if (count == 10) break;
        //pass model to view
   });

unfortunately break does not work with each() API of underscore.js Refer here: how to break the _.each function in underscore.js

How do I write a filter to pluck only top 10 from the collection

     this.collection.filter();

UPDATE: collection.first(10) fetched me filtered list. However, I still needed to chain .each() to this collection to process the collection items. collection.first() does not allow chain. Please refer to my selected answer for solution to this.

Was it helpful?

Solution

E.g.

this.collection.first(10)

Then, if you need to work with each model, e.g. :

    var collection = new Backbone.Collection([{id:1}, {id:2}, {id:3}, {id:4}, {id:5}],{model: Backbone.Model});

    var newCollection = new Backbone.Collection(collection.first(2));

    newCollection.each(function(model){
      alert(JSON.stringify(model.toJSON()));
    });

See the jsfiddle. ​ Note that there is another way to do it with the Underscore chain method as said in this topic.

Have a look at Backbone doc and Underscore doc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top