My API response:
{
firstName: '',
lastName: '',
notifications: [
{
category: '1',
subcategory: '',
source: '',
optInDate: '',
optOutDate: '',
active: ''
},
{
category: '2',
subcategory: '',
source: '',
optInDate: '',
optOutDate: '',
active: ''
}
]
}
My corresponding Backbone implementation for the response is:
var Notification = Backbone.Model.extend({
initialize: function (args) { },
});
var Notifications = Backbone.Collection.extend({
model: Notification,
url: '/xyz/abc',
parse: function (data) {
return data.notifications;
},
});
I want to only update the "category 1" model (this is always true) with say active: true
but persist the whole collection in my request payload and not just the changed model. How do we accomplish this with backbone?
I have tried getting that particular model and doing a model.set({active: true})
and calling model.save()
but that sends only that model to the server.
I need the whole response to be persisted back to the server along with the updated model.
EDIT:
I was able to achieve this with @Khang's help in his answer below. However I forgot to mention that I need to send other attributes too along with the collection i.e, firstName
, lastName
from the above response.
I'm overriding the parse
method to include them as below:
parse: function(data) {
this.firstName = data.firstName;
this.lastName = data.lastName;
return data.notifications;
}
When I call Backbone.sync
, it still sends just the collection in the payload. Is that because I am returning just the notifications from data object in the parse method?