最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Saving Backbone model and collection to JSON string - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question asked Jul 19, 2011 at 20:15 dchhetridchhetri 7,1366 gold badges44 silver badges57 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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(); });
}
发布评论

评论列表(0)

  1. 暂无评论