如何在 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'
最佳答案
您无法访问 Backbone.Collection
那样的方法(希望我没有错)但是你可能知道大多数 Backbone 方法都是基于 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
里面制造“东西”每个模型的方法,但如果您想返回一组过滤的城市,您可以使用 .map
并在 filteredResults
将是你的结果var filteredResults = this.collection.chain()
.filter(function(model) { return model.get('county') == yourCounty; })
.map(function(model) { return model.get('city'); })
.value();
console.log(filteredResults);
关于backbone.js - Chain Backbone.js 收集方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11776333/