Backbone localStorage and relations

795 views Asked by At

I'm having two RelationalModels, Student and School. School has many Students. All the data is to be stored in Backbone.localStorage

I need advice how the following should be done:

  • I suppose I need two collections, one for each model, Student and School?
  • I'm confused about how to store the data using localStorage. Should each collection store data in its own localStorage?
1

There are 1 answers

3
Jakob Hohlfeld On

I understand you are using Backbone.localStorage to accomplish local storage with backbone.js.

As I see it, you would need two collections - SchoolsCollection and StudentsCollection. SchoolsCollection would implement the local-storage uplink:

var SchoolsCollection = Backbone.Collection.extend({

  localStorage: new Backbone.LocalStorage("schools")

});

Within SchoolsCollection you would save models of type SchoolModel. Instances of SchoolModel would carry an attribute named students, beeing an instance of StudentsCollection.

This would result in the localstorage look something similar like

key: schools
value: afe5a7bd,afe5a7bd

key: schools-afe5a7bd
value: {"name":"MIT","students":[{"name":"Joe"}],"id":"afe5a7bd"}

key: schools-afe5a7bd
value: {"name":"Eaton","students":[{"name":"Max"}],"id":"afe5a7bd"}

As you can see, StudentModel looses its type on serialization. You have to implement parse() in SchoolModel to complement this effect:

var SchoolModel = Backbone.Model.extend({
    parse: function(response) {
        return _.extend({}, response, {
            students: new StudentCollection(response.students)
        });
    }
});

A single school model gets restored by parse() with a custom treatment of it's attribute students. A new StudentsCollection is beeing created with the array of objects containing key-value-pairs describing each student's model.