Saving Backbone model and collection to JSON string

本小妞迷上赌 提交于 2019-12-08 19:28:48

问题


I'm having problem saving Backbone.Model or Backbone.Collection objects to local storage. The problem is that when it saves, only the attributes gets saved and I do not want that. I'm actually using the backbone-localstorage thats provided in their sample TODO demo.

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 only the models or the collection's attributes gets sets. Is there a way to specify that I want to save the whole state the model and collection is in, not just the attributes?


回答1:


Override the Model.toJSON or Collection.toJSON to return the data you want serialized.

The default Model.toJSON just returns the attributes:

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

the Collection's toJSON utilizes the Model's toJSON:

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


来源:https://stackoverflow.com/questions/6753512/saving-backbone-model-and-collection-to-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!