I've extended the Backbone Collection class to include a "save" method, which is essentially a proxy to sync. Whenever, "save" is executed an array of objects is submitted to the backend. However, the backend is not currently structured to handle straight collections, it expects objects. Does anyone have any suggestions on how can I "wrap" this collection in a object?
I tried:
var objectCollection = {};
objectCollection['key'] = backboneCollection.models;
But the above results in "model does not have a toJSON method" error -- since I'm simply proxying sync. Thanks.
To provide a custom format for Backbone.sync, you will have to pass your data as a JSON string and provide the correct contentType. Something like this:
var M=Backbone.Collection.extend({
url: '/echo/json/',
save: function() {
var data={}, opts= {};
data.key=this.toJSON();
opts.contentType = 'application/json';
opts.data = JSON.stringify(data);
Backbone.sync.call(this,'update',this, opts);
}
});
And a Fiddle http://jsfiddle.net/xx4pr/ (check your console to see the request)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With