Sorry if this is a bit confusing ... I'm still learning Backbone.js ...
What is the right way to load and save Backbone models that have submodels within themselves? (And should I have submodels?)
For example (pardon the coffeescript) if I have something like:
class Address extends Backbone.Model urlRoot: '/api/v1/address/' url: -> return @ urlRoot+@id +'/?format=json' defaults: {'city': '', 'state': ''} class Person extends Backbone.Model urlRoot: '/api/v1/person/' url: -> return @ urlRoot+@id +'/?format=json' defaults: { name: 'Anon', address: new Address } ... and then I do this ... dude = new Person dude.set('id',101) dude.fetch() // Response returns {name: 'The Dude', address: '/api/v1/address/1998/'} // And now, dude.get('address') is '/api/v1/address/1998' and no Address object where = new Address where.set('id',1998) where.fetch() // Response returns {city: 'Venice', state; 'CA'}
I want to say dude.fetch () and for him to get both the dude and his address, and when I call Backbone.sync ('update', dude), I want to save both the dude and his address. How?
On the backend, I use tastypie to build an api for some SQLAlchemy tables (not Django ORM), so I have a resource for the Person table and the Address table:
class AddressResource(SQLAlchemyResource): class Meta: resource_name = 'address' object_class = AddressSQLAlchemyORMClass class PersonResource(SQLAlchemyResource): address = ForeignKey(AddressResource, 'address') class Meta: resource_name = 'person' object_class = PersonSQLAlchemyORMClass
Tastypie The ForeignKey function creates a mapping that returns a URL to the specified address.
I tried to overload the Dude.parse () function to call the selection for Address (), but it didn’t work, and it felt wrong, and it raised all kinds of questions:
- Should I modify my tastypie response to include Address as a nested object?
- If I go to a nested object, should I use backbone-relational , as in the question Basic-relational models that are not created , or is this overflow?
- Should I overload the parse () or fetch () function or create my own framework. Sync () to receive the response and then do it manually?
- Since it is one-to-one, should instead use only one model instead of a submodel and send information together in one request?
Is there a standard way to do this?