How can I chain collection methods in 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
});
I tried something like this, but it's wrong:
Object[object Object],[object Object],[object Object] has no method 'groupBy'
You cannot access Backbone.Collection methods that way (hope I'm not wrong) but as you probably know most of the Backbone methods are Underscore.js based methods so that means if you look at the the source code for where method you will see it uses Underscore.js filter method, so this means you can achieve what you want doing so:
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() isn't of any use to you here, you are making "stuff" inside the .each method for each of the model but if you would like to let's say return an array of filtered cities you can do with .map and in filteredResults will be your results
var filteredResults = this.collection.chain()
.filter(function(model) { return model.get('county') == yourCounty; })
.map(function(model) { return model.get('city'); })
.value();
console.log(filteredResults);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With