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.