2012-08-02 50 views
7

如何鏈接收集方法backbone.js鏈Backbone.js收集方法

var Collection = this.collection; 
Collection = Collection.where({county: selected}); 
Collection = Collection.groupBy(function(city) { 
    return city.get('city') 
}); 
Collection.each(function(city) { 
    // each items 
}); 

我想這樣的事情,但它是錯誤的:

Object[object Object],[object Object],[object Object] has no method 'groupBy' 

回答

14

您不能訪問Backbone.Collection方法,這種方式(希望我沒有錯),但正如你可能知道大多數的骨幹方法Underscore.js爲基礎的方法,這樣意味着,如果你看一下where方法,你會看到它使用Underscore.js filter方法的源代碼,所以這意味着你可以達到你想要的東西這樣做:

var filteredResults = this.collection.chain() 
    .filter(function(model) { return model.get('county') == yourCounty; }) 
    .groupBy(function(model) { return model.get('city') }) 
    .each(function(model) { console.log(model); }) 
    .value(); 

.value()對您來說沒有任何用處,您正在爲每個模型在.each方法內製作「東西」,但如果您希望讓我們返回一組經過篩選的城市,您可以使用.mapfilteredResults將是你的結果

var filteredResults = this.collection.chain() 
    .filter(function(model) { return model.get('county') == yourCounty; }) 
    .map(function(model) { return model.get('city'); }) 
    .value(); 
console.log(filteredResults);