1

我有一个具有属性的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 无法识别此字段——它只是填充的数据。

parsemy 的函数中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 的坏消息,所以我对更简单的解决方案很感兴趣。

4

1 回答 1

2

我会监听订阅集合的事件并相应地更新订阅参数。

var User = Backbone.Model.extend({

  initialize: function () {
    this.subscriptions = new Subscriptions;
    this.subscriptions.on('add remove', this.updateSubscriptions, this)
  },

  updateSubscriptions: function() {
    this.set('subscriptions', this.subscriptions.pluck('id'))
  },

  parse: function (response) {
    this.subscriptions.reset(response.__subscriptions);
    return Backbone.Model.parse.call(this, response);
  }

});

因此,删除订阅将更新subscriptions用户模型的属性:

user.subscriptions.remove(subscription)
于 2013-05-05T10:37:30.087 回答