2013-05-31 87 views
1

我想过滤模型的集合,但过滤器似乎只是返回一个对象而不是集合。从我读过的,在_()中包装过滤器函数将强制它使用内置在过滤器中的underscore.js,并返回相同的类型。但这似乎并没有奏效。代码在下面,有什么想法?Backbone.js过滤器集合返回一个对象,而不是集合

var clients = this.get('clients') 

    if (clients instanceof Backbone.Collection) { 
     console.log('clients is a collection'); 
    } else if (_.isObject(clients)) { 
     console.log('clients is an object'); 
    } else if (_.isArray(clients)) { 
     console.log('clients is an array'); 
    } else { 
     console.log('clients is not known'); 
    } 

    clients = _(clients.filter(function (client) { 
     return client.get('case_studies').length; 
    })); 

    if (clients instanceof Backbone.Collection) { 
     console.log('clients is a collection'); 
    } else if (_.isObject(clients)) { 
     console.log('clients is an object'); 
    } else if (_.isArray(clients)) { 
     console.log('clients is an array'); 
    } else { 
     console.log('clients is not known'); 
    } 

这是我的输出:

clients is a collection 
    clients is an object 

回答

1

假设你实例化您的收藏clients像这样:

var Client = Backbone.Model.extend({}); 
var Clients = Backbone.Collection.extend({ 
    model: Client 
}); 
var clients = new Clients(); 

然后,所有你需要做的是:

clients = new Clients(clients.filter(function (client) { 
    return client.get('case_studies').length 
})); 
+0

工作完美,只是缺少一个小括号最后是sis。 – Mark26855