Reputation: 3672
I'm saving a Backbone model and the API I'm working with requires 'full=true' to be passed as well in order to work correctly. so for instance to save it need to do:
myModel.save(null, { data: { full: true} });
But if I do it this way it doesn't work and if I look at the network tab in Chrome dev tools I see [object Object] for the request:
On the other hand if I use JSON.stringify it seems to work fine:
myModel.save(null, { data: JSON.stringify({ full: true}) });
Of course I can just use JSON.stringify every time but I'd really like to know why this is happening so I can potentially create a custom Backbone.sync...
Upvotes: 1
Views: 1041
Reputation: 3672
I ended up figuring it out and I'll answer my own question here in case anybody runs into the same question.
The data object needs to eventually be a string before sending via Backbone ajax. Since in the first case I didn't do this it was coerced into a string via the native .toString() method. For example:
var obj = {};
obj.toString(); //[object Object]
Which is meaningless to the API.
In the second case because I stringified the data object it worked fine.
Backbone.sync does stringify the data object with the model attributes but it's overridden if you pass an explicit data object:
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
params.contentType = 'application/json';
params.data = JSON.stringify(options.attrs || model.toJSON(options));
}
Upvotes: 3