0

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?
user1121487
  • 2,464
  • 8
  • 36
  • 61

1 Answers1

2

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.

jhohlfeld
  • 1,438
  • 1
  • 16
  • 28
  • If I don't specify localStorage property in my StudentsCollection as well, I'll get "Error: A "url" property or function must be specified". Also, I don't really understand how the StudentModel get stored this way... If I wanna fetch a collection with all Students in a view, do I have to loop through the Schools students attribute? – user1121487 Dec 06 '13 at 10:55
  • @user1121487 be careful not to use methods like `create()` on the nested collections - this may be the cause of the mentioned error. use methods that don't do unnecessary syncing like `add()`. for accessing your models you might try this for the first school/the first student: `schools.at(0).get('students').at(0)` – jhohlfeld Dec 06 '13 at 18:18
  • I met the same problem recently and block me for a long time. I think the parse() method should be the keypoint. But not so familiar with Backbone yet, so how to do this? Can you give more hints? – Chris Bao Nov 28 '16 at 09:52