2013-05-31 89 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