Alex Rivera | Logout

A Backbone.js Collection of multiple Model subclasses

Asked 2011-08-03T21:28:04.107
63

I have a REST Json API that returns a list "logbooks". There are many types of logbooks that implement different but similar behavior. The server side implementation of this on the Database layer is a sort of Single Table Inheritance, so each JSON representation of a logbook contains its "type" :

[
  {"type": "ULM", "name": "My uml logbook", ... , specific_uml_logbook_attr: ...},
  {"type": "Plane", "name": "My plane logbook", ... , specific_plane_logbook_attr: ...}
]

I would like to replicate this server model on the client side, so I have a base Logbook class and multiple logbook sub classes :

class Logbook extends Backbone.Model

class UmlLogbook extends Logbook

class PlaneLogbook extends Logbook

...

My Backbone.Collection is a set of Logbook models that i use to query the JSON API :

class LogbookCollection extends Backbone.Collection
  model: Logbook
  url: "/api/logbooks"

When I fetch the logbook collection, is there a way to cast each Logbook to its corresponding sub class (based on the JSON "type" attribute) ?

Edit
Report

1 Answer

3

as of backbone 0.9.1, i've started using the method described in esa-matti suuronen's pull-request:

https://github.com/documentcloud/backbone/pull/1148

after applying the patch, your collection would be something like this:

LogbookCollection = Backbone.Collection.extend({

    model: Logbook,

    createModel: function (attrs, options) {
        if (attrs.type === "UML") { // i'am assuming ULM was a typo
            return new UmlLogbook(attrs, options);
        } else if (attrs.type === "Plane") {
            return new Plane(attrs, options);
        } else {
            return new Logbook(attrs, options);
            // or throw an error on an unrecognized type
            // throw new Error("Bad type: " + attrs.type);
        }
    }

});

i believe this would fit since you're using STI (all models have unique ids)

answered 2012-03-31T16:32:46.883

Your Answer