user1121487
user1121487

Reputation: 2680

Backbone localStorage and relations

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:

Upvotes: 0

Views: 796

Answers (1)

Jakob Hohlfeld
Jakob Hohlfeld

Reputation: 1564

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.

Upvotes: 2

Related Questions