Saving the base model and collection to a JSON string

I'm having trouble saving Backbone.Model or Backbone.Collection objects to local storage. The problem is that only attributes are saved when saved, and I don't want this. I actually use base-localstorage, which is represented in their TODO sample.

This is their save function.

save: function() { localStorage.setItem(this.name, JSON.stringify(this.data)); } 

When I look at what JSON.stringify (this.data) returns, I see that only models or collection attributes receive sets. Is there a way to indicate that I want to save all the state of the model and collection, and not just attributes?

+7
source share
1 answer

Flip Model.toJSON or Collection.toJSON to return the data you want to serialize.

By default, Model.toJSON simply returns attributes:

 toJSON : function() { return _.clone(this.attributes); } 

The toJSON collection uses the toJSON model:

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

All Articles