0

我正在尝试将模型添加到集合中,该集合将通过 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, . . . })
4

2 回答 2

0

要将模型添加到集合中,您应该使用该add函数。

这会将模型添加到集合中,但是 localStorage 还没有同步。

要将添加的模型持久保存到 localStorage,您必须调用model.save().

于 2014-10-08T22:24:06.947 回答
0

使用add代替create

http://backbonejs.org/#Collection-create collection.create(attributes, [options])

http://backbonejs.org/#Collection-add collection.add(models, [options])

于 2014-10-07T17:07:49.957 回答