2011-05-20 28 views
2

首先,對於標題的歉意 - 如果任何人有閱讀問題後,一個更好的版本,請修改或問我。動態創建的集電的情況下

我已經擴展了「其中」方法,讓我在集合中的模型執行_.select核心骨幹集合對象。目前,這將返回一個包含這些模型的新的vanilla Collection對象。我想要的是返回同一個類型的集合對象,因爲我調用方法...

 
Backbone.Collection.prototype.where = function(a) { 
    var execute = function(item) { 
    ... 
    }; 

    return new Backbone.Collection(this.select(execute)); 
}; 

var Accounts = Backbone.Collection.extend({...}) 

我想要什麼,在return語句要返回一個新的賬戶集合。但我不想在每個擴展集合中定義或擴展此方法。類似以下僞代碼:

 
return new instanceof this(this.select(execute)); 

有意義嗎?

回答

1

我不是100%肯定你是問什麼,但我想你想在一個集合的實例運行「其中」,並得到一個新的集合。只是玩弄的螢火,並想出了這個:

var Chapter = Backbone.Model; 
var chapters = new Backbone.Collection; 

chapters.comparator = function(chapter) { 
    return chapter.get("page"); 
}; 

chapters.add(new Chapter({page: 9, title: "The End"})); 
chapters.add(new Chapter({page: 5, title: "The Middle"})); 
chapters.add(new Chapter({page: 1, title: "The Beginning"})); 

Backbone.Collection.prototype.where = function(selector) { 
var newCol = new this.__proto__.constructor(); 
var itemsToInsert = this.select(selector); 
itemsToInsert.forEach(function(item){ newCol.add(item) }); 
return newCol; 
}; 

chapters.where(function(c){ return c.get('page') == 1 }); 

`

這也許可以做得更好。但是,這似乎功能。

+0

爲我們交換我的代碼會在應用程序中產生更多的錯誤,所以我猜猜這個代碼沒有返回正確的集合。 – beseku 2011-05-20 04:02:03

+0

是的,我不確定是否我創建newCol的方式是正確的方式來做到這一點...什麼樣的錯誤?可能能夠弄清楚。螢火蟲檢查顯示,它看起來像是一個骨幹收集。 – 2011-05-20 04:17:37

+0

是的,檢查它看起來像一個集合,但然後試圖運行收集方法,它會拋出錯誤,說他們是未定義的。現在我會盡我所能去做這件事。 – beseku 2011-05-20 07:44:34

相關問題