I have a BackboneJS collection called History which can contain one of several Backbone JS models (which extend from HistoryItem which extends from Backbone.Model), I trying to find a way to have this recreated when loading, unfortunately it seems BackboneJS collection can only specify at particular model e.g.
HistoryCollection = Backbone.Model.extend({
model: app.models.HistoryItem
})
What I really need to do is determine this per type, here is what I'd like to do
HistoryCollection = Backbone.Model.extend({
model: function(item) {
return app.models[item.type]; } })
Any ideas before I fork Backbone to implement this? (i.e. a collection model attribute being able to take a function)
I've just implemented this feature and started off with Jake Dempsey's advice, however you actually need to override a different method in the collection. This is the code I used:
Note that it is a private(ish) method so something to keep in mind when upgrading Backbone.
Playing around in firebug.. came up with an approach where you can override the parse method of collection instead of specifying the model. Your parse implementation basically becomes a simple factory for filling the collection with models that you want:
IMHO, I prefer to play with the model method in the collection:
or using a proxy model: