I have a collection of Animals.
App.Collections.Animals extends Backbone.Collection
model: App.Animal
url: '/animals/' #returns json
And these animal classes:
App.Models.Animal extends Backbone.Model
App.Models.Monkey extends App.Models.Animal
defaults:{type:'Monkey'}
App.Models.Cat extends App.Models.Animal
defaults:{type:'Cat'}
App.Models.Dog extends App.Models.Animal
defaults:{type:'Dog'}
When collection is filled with JSON (records contain the type attribute) I want models to be instantiated as sub-classed models (Monkey,Cat,Dog) and not as Animal. How can you achieve this?
Override backbone collection's _prepareModel. The collection new uses subclasses when defined otherwise uses the default model.
The solution is straightforward (pardon the JS, I don't know CoffeeScript):
You have to:
Here is a JSFiddle that shows this polymorphic collection in action: http://jsfiddle.net/FiddlerOnTheTarmac/uR2Sa/
From Backbone documentation: