Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Wrap Backbone Collection into JSON object?

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.

like image 1000
Ari Avatar asked Dec 28 '25 21:12

Ari


1 Answers

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)

like image 144
nikoshr Avatar answered Dec 30 '25 11:12

nikoshr