Asked By: Anonymous
just a very short question on using Backbone.js with LocalStorage:
I’m storing a list of things (Backbone collection) in LocalStorage. When my website is open in multiple browser windows / tabs and the user in both windows adds something to the list, one window’s changes will overwrite the changes made in the other window.
If you want to try for yourself, just use the example Backbone.js Todo app:
- Open http://backbonejs.org/examples/todos/index.html in two browser tabs
- Add an item ‘item1’ in the first tab and ‘item2’ in the second tab
- Refresh both tabs: ‘item1’ will disappear and you’ll be left with ‘item2’ only
Any suggestions how to prevent this from happening, any standard way to deal with this?
Thxx
Solution
Answered By: Anonymous
The issue is well-known concurrency lost updates problem, see Lost update in Concurrency control?.
Just for your understanding I might propose the following quick and dirty fix, file backbone-localstorage.js
, Store.prototype.save
:
save: function() {
// reread data right before writing
var store = localStorage.getItem(this.name);
var data = (store && JSON.parse(store)) || {};
// we may choose what is overwritten with what here
_.extend(this.data, data);
localStorage.setItem(this.name, JSON.stringify(this.data));
}
For the latest Github version of Backbone localStorage, I think this should look like this:
save: function() {
var store = this.localStorage().getItem(this.name);
var records = (store && store.split(",")) || [];
var all = _.union(records, this.records);
this.localStorage().setItem(this.name, all.join(","));
}