Adding model to Backbone.localstorage Collection

310 Views Asked by At

I am trying to add a model to a collection which will be stored in local storage via the Backbone.localstorage plugin.

The code for adding the model in the collection is as follows:

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;
});

The model is:

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;
});

The problem is that the model is not being saved to local storage. It only saves to local storage when I use "this.create({id: model.id});" but missing all other attributes.

The model being passed to addArticle(model) is the same as the one it's expecting, can anyone give some help on how to persist this data to local storage ?

I would hate to write the following since it is already in that form:

this.create({id: model.id, title:model.title, . . . })
2

There are 2 best solutions below

2
coding_idiot On

Use add instead of create

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

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

0
c05mic On

To add the model to the collection, you should be using the add function.

This adds the model to the collection, but the sync doesn't happen to the localStorage yet.

To persist the added model to the localStorage, you have to call model.save().

HTH!