Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newly saved Backbone model does not appear in collection after fetch

I am using backbone local storage and experiencing some weird behavior.

I have a Model and Collection that is defined, instantiated, and fetched:

MyModel = Backbone.Model.extend({
        localStorage: new LocalStore('example-myModels')
        //note: LocalStore = Backbone.LocalStore -> https://github.com/jeromegn/Backbone.localStorage
});

MyCollection = Backbone.Collection.extend({
        model : MyModel,
        localStorage: new LocalStore('example-myModels')
});

var myCollection = new MyCollection();
myCollection.fetch(...);

This collection is then displayed as a list to the user. The user is able to "add" an item to the collection which eventually results in this code:

var newModel = new MyModel();
newModel.save(newModelAttributes, {
    success: function(newlySavedModel) {
        myCollection.add(newlySavedModel);
    }
);

At this point myCollection has the newly added model and I can see the record successfully created in my localStorage database:

Pre-save LocalStorage:

enter image description here

Post-save LocalStorage:

enter image description here

The next step after the user adds the record is to go back to the list, at which point the collection is fetched again:

myCollection.fetch();

Now myCollection no longer contains the new record. No matter how many times I fetch, the new record will not be retrieved - even though I can see it in my localStorage database. I have also tried creating a new instance of the Collection and fetching that but it yields the same results. If I reload the browser, the new record appears as expected. Anyone have any idea what is going on? I get the feeling I am missing something fundamental here...

A running example that reproduces the issue is available here: http://jsbin.com/iyorax/2/edit (make sure the console is visible and click "Run with JS")

Thanks in advance!

like image 965
moliveira Avatar asked Jun 13 '13 20:06

moliveira


2 Answers

Your model and your collection need to share a reference to the same instance of LocalStore, whereas right now you are creating two different objects. To fix this, create the LocalStore object outside of either model or collection, and pass in a reference to it in the constructors of your Model and collection.

like image 174
Lyn Headley Avatar answered Nov 07 '22 18:11

Lyn Headley


I have an application working with Backbone.localstorage and what works for me is I first add the model to the collection and then I call save to the model. like this.

var newModel = new MyModel();
myCollection.add(newModel)
newModel.save();

Im not 100% sure, but my reasoning is that, your model is saved, but your collection is not, and perhaps an index is not being updated and at the time that you call fetch you are getting the unupdated collection.

Hope that helps.

like image 1
Rayweb_on Avatar answered Nov 07 '22 18:11

Rayweb_on