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
model.set(obj)
. – Emile Bergeron