0

I am using backbone.js in my mvc application and I have a scenario where I have to pass an array to my Post method in Rest API . I am trying to set an array property in my model and then calling this.collection.create(model). I am using properties of models like this

defaults: {
            Address: '',
            City: '',
            State: '',
            Zip: '',
            AddressArray: []
        } 
  
and trying to call Post method as
    e.models[0].set({ 'AddressArray': e.models});
    this.collection.create(e.models[0]);
    
Here e.models[0] is my object of my model and e.models is an array of models. The set property sets array address but then on create it is giving this error.
Uncaught TypeError: Converting circular structure to JSON 

Please guide.

touseefkhan4pk
  • 473
  • 4
  • 26
  • possible duplicate of ["How" to save an entire collection in Backbone.js - Backbone.sync or jQuery.ajax?](http://stackoverflow.com/questions/6879138/how-to-save-an-entire-collection-in-backbone-js-backbone-sync-or-jquery-ajax) – McGarnagle Dec 10 '12 at 17:06

1 Answers1

0

The error just means you've created a self-referencing object (such can't possibly be serialized to JSON). Ie, you've done the equivalent of this:

var x = {};
x['test'] = x;
JSON.stringify(x); // TypeError: Converting circular structure to JSON

You could create a copy of the model first, using toJSON, so that the object doesn't reference itself:

var json = e.models[0].toJSON();
json['AddressArray'] = e.models[0].attributes;
this.collection.create(json);

But this doesn't quite make sense, because .attributes refers to the model's properties, so all you're doing is creating a duplicate of the model under AddressArray, ie, if model is say { prop: "val", prop2: "val2" }, then you just end up with:

{
    prop: "val",
    prop2: "val2",
    AddressArray: {
        prop: "val",
        prop2: "val2",
    }
}

Either way, you can't convert an object that references itself to JSON; and serialization is required save a model to the server by calling Collection.create.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • Hi dbaseman you are right. But actualy I have array of models at client side which I want to send on server side in Post method. Please guide How will I send array of models to Post method of Rest API as I don't have much idea of backbone.js. – touseefkhan4pk Dec 10 '12 at 12:02
  • @touseefkhan4pk see this question, where the accepted answer is to create another model that contains your collection, and override its `toJSON` method: http://stackoverflow.com/q/6879138/1001985 – McGarnagle Dec 10 '12 at 17:07