节省骨干模型和集合JSON字符串 [英] Saving Backbone model and collection to JSON string

查看:96
本文介绍了节省骨干模型和集合JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,节省Backbone.Model或Backbone.Collection对象到本地存储。
问题是,当它的扑救,只是属性被保存,我不希望出现这种情况。
实际上,我用自己的样品TODO演示提供了基础,这就是的localStorage

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.

这是他们的保存功能

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

当我在看什么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?

推荐答案

重写Model.toJSON或Collection.toJSON返回数据你想序列化。

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

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

The default Model.toJSON just returns the attributes:

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

集合的的toJSON利用模特的toJSON:

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

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

这篇关于节省骨干模型和集合JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆