3

When I use the Backbone.Collection.where function to filter the collection I get an array of models as return value but not an other filtered collection object. So I can't use other collection functions with that.

What is the purpose of such behavior?

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
fey
  • 1,289
  • 1
  • 10
  • 20

2 Answers2

6

where isn't the only method that returns an Array. where returns a new Array because you definitely don't want it mutating your existing Collection automatically. Also, many times you may want the result in Array form.

For whatever reason, the BB devs decided that it was better to return a new Array rather than a new Collection. One thought could be that, perhaps the returned data would be used in a different type of Collection. Another reason could be so that you always know what is returned from one of these methods. 2+ types of collections will ALWAYS return Arrays from these types of methods rather than having to try and inspect via instanceof or something else that isn't very reliable.

Edit

In addition, you COULD make your collections behave in a manner where you return new Collections. Create a base Collection to do something like this:

// Override the following methods
var override = ["where","find",...];
var collectionProto = Backbone.Collection.prototype;
BaseCollection = Backbone.Collection.extend({});
for (var key in collectionProto) {
    if (collectionProto.hasOwnProperty(key) && override.indexOf(key) > -1) {
        BaseCollection.prototype[key] = function () {
            return new this.constructor(collectionProto[key].apply(this, arguments);
        };
    }
}

Instead over extending off Backbone.Collection, extend off BaseCollection.

Trevor
  • 11,269
  • 2
  • 33
  • 40
  • I've added some extra context for making collections behave the way you might want them too. – Trevor Dec 26 '12 at 14:35
0

Note that you can still use most of the underscore utilities on arrays. Here's how to use each() after a filter()

_.each( MyCollection.filter( filter_fn() {} ), each_fn() {} )

Stephen Thomas
  • 13,843
  • 2
  • 32
  • 53