0
votes

I am building a Cordova App for iOS and Android. Therefore I am using Backbone with Backbone.LocalStorage to store my data on the device.

My Collections and Models look like this

App.collections.Articles = Backbone.Collection.extend({
    model: App.models.Article,
    localStorage: new Backbone.LocalStorage("articles"),
});

App.models.Article = Backbone.Model.extend({
    defaults:{
        read: false,
    },
});

I have an ajax call to get my data from a drupal system. After I got my data, I save it to the collections by using this little code.

    App.data.Articles = new App.collections.Articles();  

    $.each(data.articles, function(i,obj) {
        var model = App.data.Articles.add(obj);
        model.set({read: true});
        model.save();
    });

So I get my data from the ajax call and create a model, which I add to my collection. After that I "save" the model to the backbone localstorage.

Everything works fine. I can fetch my collection later and use the local data, when no internet is available. The only thing that is not working is, that my model won't update. So it does not recognize that the data from the ajax call is new or has changed. If I do "add", it will add a whole new model. Because the Backbone.localStorage uses it's own idAttribute on the saved models. So it does not recognize that the model already exists and that it only should update the model.

What can I do ? Is there a way to compare the model id and the localStorage id.

This is what my stored data looks like. It creates an "articles" object with all IDs. And it creates each article object by it's new ID.

articles: cfbc6a16-c3c4-cb1b-6667-fb1ecf00717f,da65ce5a-dbbb-d8ca-4117-50d0a0fa3bf4,f2af3c83-bd3c-de87-7953-d992348c46cc,9a3ca688-0ba9-ee87-4fb3-878d1eca46bc,f1f9e082-c1ff-5d6b-9c13-54ddd3a12158

articles-9a3ca688-0ba9-ee87-4fb3-878d1eca46bc
1
You should get each model from the local collection with the id from the backend, if it exist, just update it manually model.set(obj).Emile Bergeron

1 Answers

1
votes

You can probably use

Collection.set

The set method performs a "smart" update of the collection with the passed list of models. If a model in the list isn't yet in the collection it will be added; if the model is already in the collection its attributes will be merged; and if the collection contains any models that aren't present in the list, they'll be removed. All of the appropriate "add", "remove", and "change" events are fired as this happens. Returns the touched models in the collection. If you'd like to customize the behavior, you can disable it with options: {add: false}, {remove: false}, or {merge: false}.