2012-05-24 61 views
5

如果我有一個Backbone集合,並希望創建該集合的副本並篩選出某些條目,那麼如何才能將複製的實例保留爲Backbone.Collection?骨幹過濾

實施例:

var Module = Backbone.Model.extend(); 

var ModuleCollection = Backbone.Collection.​extend({ 
    model: Module 
}); 

​var modules = new ModuleCollection; 

​modules.add({foo: 'foo'​​​​​​},{foo: 'bar'});​​​​​ 

console.log(modules instanceof Backbone.Collection); // true 

var filtered = modules.filter(function(module) { 
    return module.get('foo') == 'bar'; 
}); 

console.log(filtered instanceof Backbone.Collection); // false 

http://jsfiddle.net/m9eTY/

在上面的例子中,我想filtered是模塊的濾波版本,而不是僅僅的模型的陣列。

本質上我想在集合實例中創建一個方法,它可以過濾掉某些模型並返回Backbone.Collection實例,但只要我開始過濾迭代方法就會返回一個數組。

回答

9

如果需要,可以將過濾的數組封裝在臨時ModuleCollection中,過濾的模型與原始ModuleCollection中的模型是相同的實例,因此如果模塊的屬性發生更改,它仍會被兩個集合引用。

所以你做什麼,我的建議是這樣的:

var filtered = new ModuleCollection(modules.filter(function (module) { 
    return module.get('foo') == 'bar'; 
})); 

由於骨幹0.9.2有一個叫where額外的方法,做同樣的:

var filtered = modules.where({foo: 'bar'}); 

仍然返回一個數組雖然如此,你仍然需要把它包裝成這樣:

var filtered = new ModuleCollection(modules.where({foo: 'bar'})); 
+0

有道理。謝謝! – David

0

對於FIL的TeringBay收集利用骨幹

爲了讓你應該有一個過濾功能的集合中的過濾器

var MyCollection = Backbone.Collection.extend ({ 
    filtered : function() { 

我建議使用下劃線過濾器,將用於有效和虛假的無效返回true其中真正的是你是什麼尋找。使用this.models來獲取當前收集模型使用model.get(「」),以得到你想要檢查

var results = _.filter(this.models, function (model) {   
    if (model.get('foo') == 'bar') 
    return true ; 
    return false ; 
}); 

然後用下劃線映射您的結果,並把它轉換爲JSON元素一樣,這是probally哪裏你犯錯

results = _.map(results, function(model) { return model.toJSON() }); 

最後返回僅結果的新骨幹集合,這是如何做一個複製的集合

return new Backbone.Collection(results) ;