Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Collection of polymorphic Models

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?

like image 411
Andreyy Avatar asked Mar 20 '13 15:03

Andreyy


1 Answers

From Backbone documentation:

A collection can also contain polymorphic models by overriding this property with a function that returns a model.

var Library = Backbone.Collection.extend({

  model: function(attrs, options) {
    if (condition) {
      return new PublicDocument(attrs, options);
    } else {
      return new PrivateDocument(attrs, options);
    }
  }

});
like image 133
Eran Medan Avatar answered Sep 28 '22 06:09

Eran Medan