In backbone what is the desired way to store the relationship (in localstorage) between an author and books.
Is it possible to have a collection as an attribute or should an array be used or...?
var book = Backbone.Model.extend({
defaults:{
title: ''
}
});
var books = Backbone.Collection.extend({
model: book
});
var author = Backbone.Model.extend({
defaults:{
firstName: '',
lastName: '',
books: new books()
}
});
var authors = Backbone.Collection.extend({
model: author,
localStorage: new Backbone.LocalStorage("authors")
});
There is no One True Way of handling nested collections in Backbone. Quoting from Backbone FAQ:
The FAQ also suggests one pattern and provides a link to the Extensions, Plugins, Resources page, which links to many libraries you can use for handling nested models and model relations.
That said, I have sometimes approached the problem like this:
The comments hopefully explain how it works, but the point is that you can use the model as you would normally: initialize the children with a collection, an array or nothing, get the from a server, send them to the server, it should all work transparently. There's quite a bit of boilerplate code to write, but it's relatively simple to abstract into a base class, if you find yourself repeating the same code.
Edit: Small correction, you don't need the
books
defined in thedefaults
object, because the constructor creates it if missing./code sample not tested