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)