プロパティを持つUser
エンティティがありsubscriptions
ます。これは ID の配列です。
フェッチを実行すると、API はそれらを入力し、次のsubscriptions
ようなものを返します。
{
subscriptions: [1, 2, 3],
__subscriptions: [
{
id: 1,
name: 'Example'
},
{
id: 2,
name: 'Example'
},
{
id: 3,
name: 'Example'
}
]
}
これを行ったのは、元のアクションに対して引き続きアクションを実行し、subscriptions
それらを API に保存できるようにするためです。__subscriptions
API はこのフィールドを認識しないため、私が行った変更は永続化されません。これは単に入力されたデータです。
myのparse
関数で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 について悪いことを聞いたので、より簡単なソリューションに興味がありました。