我正在尝试将模型添加到集合中,该集合将通过 Backbone.localstorage 插件存储在本地存储中。
在集合中添加模型的代码如下:
define([ 'jquery', 'underscore', 'model/articleModel', 'backbone', 'localstorage' ], function($, _, itsModel, Backbone) {
var articleCache = Backbone.Collection.extend({
model: itsModel,
localStorage: new Backbone.LocalStorage("articles-backbone-cache"),
addArticle: function(model){
console.log('Adding new article ID [' + model.id + '] Title [' + model.title + '] to cache via backbone.localstorage');
console.log(model);
//CRUCIAL PART
this.create(model); // Doesn't work
this.create(model.toJSON()); //Doesn't work
this.create({id: model.id}); // Works but only id is saved and naturally all other attributes are set to defaults
}
});
return articleCache;
});
型号为:
define([ 'jquery', 'underscore', 'backbone', 'localstorage' ], function($, _, Backbone) {
var article = Backbone.Model.extend({
defaults : {
id : '0',
title : '',
subtitile : '',
date : '',
section : '',
section_id : -1,
subsection : null,
subsection_id : null,
noOfComments : 0
});
return article;
});
问题是模型没有保存到本地存储。当我使用“this.create({id:model.id});”时它只保存到本地存储 但缺少所有其他属性。
传递给 addArticle(model) 的模型与预期的模型相同,任何人都可以就如何将这些数据持久保存到本地存储提供一些帮助吗?
我不想写以下内容,因为它已经是那种形式:
this.create({id: model.id, title:model.title, . . . })