抱歉,如果这有点复杂...我仍在学习 Backbone.js...
加载和保存内部具有子模型的 Backbone 模型的正确方法是什么? (我什至应该有子模型吗?)
例如,(请原谅咖啡脚本),如果我有类似的东西:
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'}
我想要的是就是说 dude.fetch() 并让它获取这家伙和他的地址,当我调用 Backbone.sync('update',dude) 时,我想保存这家伙和他的地址。如何?
在后端,我使用 tastypie 为一些 SQLAlchemy 表(不是 Django 的 ORM)构建 api,因此我有一个用于 Person 表和 Address 表的资源:
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
美味派的外键 http://django-tastypie.readthedocs.org/en/latest/interacting.html函数创建一个返回的映射the URL到有问题的地址。
我尝试重载 Dude.parse() 函数来调用 Address() 的 fetch,但它不起作用,而且感觉不对,并且引发了各种问题:
- 我是否应该修改我的 tastypie 响应以将地址包含为嵌套对象?
- 如果我更改为嵌套对象,我应该使用骨干关系型 https://github.com/PaulUithol/Backbone-relational/,如问题中所示未创建骨干关系相关模型 https://stackoverflow.com/questions/11316782/backbone-relational-related-models-not-being-created,或者这太过分了?
- 我可以做重载 parse() http://paltman.com/2012/04/30/integration-backbonejs-tastypie/或 fetch() 函数或创建我自己的backbone.Sync() 来获取响应,然后手动执行此操作?
- 既然它是一对一的,我是否应该只使用一个模型而不是子模型,并在一个请求中将信息一起发送回来?
有这样做的标准方法吗?