Backbone Collection - 构造函数

coo*_*ool 8 backbone.js

我正在将数组传递给新集合.是否可以通过传递第二个参数来过滤数组,并检查数组中对象的attr,并仅在通过过滤器测试时创建集合.

collection = new Backbone.Collection([{name:'xy',age:24},{name:'y',age:35}])
Run Code Online (Sandbox Code Playgroud)

我是否可以仅为不到30年的对象创建集合.

nem*_*esv 5

在传入集合之前,可以在数组上使用_.filter

collection = new Backbone.Collection(
     _.filter([{name:'xy',age:24},{name:'y',age:35}], 
              function(item) { return item.age < 30; }));
Run Code Online (Sandbox Code Playgroud)

或者,您可以将自定义过滤逻辑移动到您的集合中initialize,您将获得models可以修改/过滤的阵列

var Under30 = Backbone.Collection.extend({
    initialize: function(models, options) {
        for(var i = models.length - 1; i > 0; i-- ){
            if (models[i].age > 30){
                models.splice(i,1);
            }
        }
    }
});

var collection = new Under30([{name:'xy',age:24}, {name:'y',age:35}]);
console.log(collection.models.length); // will be 1
Run Code Online (Sandbox Code Playgroud)

演示JSFiddle.

您可以通过在options参数中提供过滤谓词来扩展它

var FilteredCollection = Backbone.Collection.extend({
        initialize: function(models, options) {
            for(var i = models.length - 1; i > 0; i-- ){
                if (options.filter && options.filter(models[i])){
                    models.splice(i,1);
                }
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

并使用它

var collection = new FilteredCollection(
      [{name:'xy',age:24}, {name:'y',age:35}], 
      {
          filter: function(item) { 
              return item.age > 30; 
          }
      }
);
console.log(collection.models.length); // will be 1
Run Code Online (Sandbox Code Playgroud)