Search code examples
javascriptbackbone.jstypescriptbackbone.js-collections

Backbone.Collection get first n as new collection


I have a Backbone.Collection which has been set up like so:

let col = new Backbone.Collection();

let model1 = new Backbone.Model();
model1.set('name', 'first');
col.add(model1);

let model2 = new Backbone.Model();
model2.set('name', 'second');
col.add(model2);

let model3 = new Backbone.Model();
model3.set('name', 'third');
col.add(model3);

When I attempt to select the first 2 models from the collection with this:

let firstTwo = col.first(2);

firstTwo contains model1 and model2 as an array.

How can I get the first two as a Backbone.Collection without manually adding them all to a new collection?


Solution

  • You have to create a new Collection & add them. The good news is creating a new collection is very inexpensive, and the model instances will be the same ones in both the full and partial collection.

    Collections automatically have some Underscore methods built into them. But these method all return arrays of Model objects. If you want to instead get a Collection instance, your best bet is to create another method on your Collection class. You can still use the Underscore methods to do the filtering, however.

    var MyCollection = Backbone.Collection.extend({
        // ...
        firstAsCollection: function(numItems) {
            var models = this.first(numItems);
            return new MyCollection(models);
        }
    });