1
votes

I would like to know how exactly a serialisation into JSON of a Backbone collection which contains attributes and models could be performed.

So per example if I have a collection like this:

var myCollection = Backbone.Collection.extend({

   initialize: function (attr, options) {
      this.property = options.property;
   } 
});

When trying to stringify with the JSON.stringify(myCollection) function, the stringify will call the object toJSON method defined in the Backbone Collection Object. Backbone collection defines this method as follows:

toJSON : function() {
   return this.map(function(model){ return model.toJSON(); });
}

This means that only the models included in the collection will be included in the result JSON object but not the attributes of the collection I previously defined.

Do you know who this could be achieved?

Thanks.

Edit: Maybe not clear enough in my original question, I know I could override the toJSON method my questions is how exactly do it to achieve what I need in a general matter (not only for this specific attribute but imagine I have another collections which contains other properties, and all of them inherit from a baseCollection object. More over I would like to know how to restore that JSON object back to the backbone original state (not sure if by creating a new collection passing the JSON object in the parameters of the constructor would do the trick with this attributes)

2

2 Answers

0
votes

You could override the "toJSON" method in your MyCollection class and return the string that you want.

0
votes

You could override the toJSON method like @trunal-bhanse said, but if your goal is to sync that data with your server then you should probably find a better way of representing that data. Backbone Collections by default return an array when you call toJSON on an instance of one. That array then gets converted into a string using JSON.stringify before being sent to the server. However, the JSON.stringify method will not include any properties you've set on the array:

var test = ["foo", "bar", "baz"];
test.Hello = "World!";
console.log(test);    //  ["foo", "bar", "baz", Hello: "World!"]
JSON.stringify(test); // '["foo", "bar", "baz"]'