Reputation: 915
Firstly, apologies for the title - if anyone has a better version after reading the question, please edit or ask me to.
I have extended the core Backbone Collection object with a 'where' method that allows me to perform an _.select on the models within the collection. Currently this returns a new vanilla Collection object containing the models. What I want is for the method to return a Collection object of the same type as I am calling ...
Backbone.Collection.prototype.where = function(a) { var execute = function(item) { ... }; return new Backbone.Collection(this.select(execute)); }; var Accounts = Backbone.Collection.extend({...})
What I want, at the return statement is to be returning a new Account collection. But I don't want to have to define or extend this method in each collection I extend. Something like the following pseudo code:
return new instanceof this(this.select(execute));
Make sense?
Upvotes: 2
Views: 221
Reputation: 6312
Im not 100% sure of what you are asking, but I think you want to run a 'where' on an instance of a collection and get back a NEW collection. Was just playing around in firebug and came up with this:
var Chapter = Backbone.Model;
var chapters = new Backbone.Collection;
chapters.comparator = function(chapter) {
return chapter.get("page");
};
chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));
Backbone.Collection.prototype.where = function(selector) {
var newCol = new this.__proto__.constructor();
var itemsToInsert = this.select(selector);
itemsToInsert.forEach(function(item){ newCol.add(item) });
return newCol;
};
chapters.where(function(c){ return c.get('page') == 1 });
`
This could probably be done better.. but this seems functional.
Upvotes: 1