Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain Backbone.js collection method

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' 
like image 302
user1344853 Avatar asked Aug 02 '12 11:08

user1344853


1 Answers

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);
like image 159
Claudiu Hojda Avatar answered Nov 26 '22 02:11

Claudiu Hojda