Backbone.Collection 获取前 n 个作为新集合

Backbone.Collection get first n as new collection

我有一个 Backbone.Collection 是这样设置的:

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

当我尝试 select 集合中的前 2 个模型时:

let firstTwo = col.first(2);

firstTwo 包含 model1model2 作为数组。

如何在不手动将它们全部添加到新集合的情况下将前两个作为 Backbone.Collection 获取?

您可以在 col 模型中创建一个函数,其行为应类似于以下内容:

sublist: function (numberOfElements) {
     var i = 0;
     return this.filter(function (model) {
                if (i <= numberOfElements){
                    return true;
                }
                return false;
     });
}    

您必须创建一个新的 Collection 并添加它们。好消息是创建一个新的 collection 非常便宜,并且模型实例在完整和部分 collection 中都是相同的。

Collections 自动内置了一些 Underscore 方法。但是这些方法都是模型 objects 的 return 个数组。如果您想改为获取 Collection 实例,最好的办法是在 Collection class 上创建另一个方法。但是,您仍然可以使用 Underscore 方法进行过滤。

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