javascript 将 Backbone 模型和集合保存为 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6753512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:43:35  来源:igfitidea点击:

Saving Backbone model and collection to JSON string

javascriptjqueryjsonsavebackbone.js

提问by dchhetri

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.

我在将 Backbone.Model 或 Backbone.Collection 对象保存到本地存储时遇到问题。问题是,当它保存时,只有属性被保存,我不希望那样。我实际上正在使用他们的示例 TODO 演示中提供的主干本地存储。

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?

当我查看 JSON.stringify(this.data) 返回的内容时,我只看到模型或集合的属性获取集合。有没有办法指定我要保存模型和集合所处的整个状态,而不仅仅是属性?

回答by Edward M Smith

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

覆盖 Model.toJSON 或 Collection.toJSON 以返回要序列化的数据。

The default Model.toJSON just returns the attributes:

默认的 Model.toJSON 只返回属性:

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

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

集合的 toJSON 使用模型的 toJSON:

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