我有一个具有属性的User
实体。subscriptions
这是一个 ID 数组。
当我执行 fetch 时,API 将填充这些subscriptions
,并返回如下内容:
{
subscriptions: [1, 2, 3],
__subscriptions: [
{
id: 1,
name: 'Example'
},
{
id: 2,
name: 'Example'
},
{
id: 3,
name: 'Example'
}
]
}
我已经这样做了,以便我仍然可以对原始文件执行操作subscriptions
,然后将它们保存回 API。我所做的任何更改__subscriptions
都不会保留,因为 API 无法识别此字段——它只是填充的数据。
在parse
my 的函数中User
,我创建了嵌套集合:
parse: function (response) {
this.subscriptions = new Subscriptions(response.__subscriptions)
}
但是,如果我想删除一个订阅,我必须从实体的subscriptions
字段中拼接它User
,然后我还必须从subscriptions
作为属性嵌套的集合中删除它User
:
// Clone the subscriptions property, delete the model with a matching ID, and then set it again.
var value = _.clone(this.get('subscriptions'))
// Use splice instead of delete so that we don't leave an undefined value
// in the array
value.splice(value.indexOf(model.id), 1)
// Also remove the same model from the nested collection
var removedSubscription = this.subscriptions.get(model)
this.subscriptions.remove(removedSubscription)
this.set('subscriptions', value)
this.save()
这有点烦人。理想情况下,从subscriptions
属性中删除 ID 应该会自动更新集合。
这似乎是处理嵌套模型和集合的好方法吗?我听说过关于 Backbone.Relational 的坏消息,所以我对更简单的解决方案很感兴趣。