Backbone.js localStorage + remote sync
github.com
github.com
Atm our users trigger syncs manually, but we're planning to move to PhoneGap network events as triggers for syncs.
I do have one suggestion, though: while it's of course not much work to compile the script to JavaScript, it couldn't hurt to include a current JS version in the repo for people who don't have Node & CoffeeScript installed.
Differences:
- it works with any .sync implementation you might already have (JSON, XML, whatever). It just drops in, caching the server responses locally, not assuming anything about how the service works
- instead of overridding Backbone.Sync I let you extend CachedModel on a per model basis (that way some models can be cached locally while others are not)
I didn't include any fancy cache expiry, just using a simple localstorage.clear on login for now.
example usage: var User = Backbone.CachedModel.extend({ cacheName: 'USERS', });
I handle not sending models to the server with remote/local boolean attributes on the model. Certainly not as well decoupled as yours.
It's a bit I inherited from Backbone.localStorage, and haven't looked into much.
If I make changes based on a model that I've read from my local cache ... while someone else edits the same model on the server ... how does that reconcile when I try later on to make a change?
I've been thinking for a little bit now that it would awesome to build a Backbone sync system that could cache things locally when the user is offline, then seamlessly handle bringing them back in sync with ShareJS.
Looking forward to seeing the offline sync helper you mentioned in another thread.
My implementation leaves a lot to be desired with regards to re-use (there are certain project requirements which happened to be met by the project I built it for) but it does nicely manage automatic replication of the most recent version of models between server and client.
As far as I can tell, this implementation reads from the local model if it exists, otherwise it loads from the server? And writes always go to the server unless explicitly told otherwise?
This just makes loading up a page even faster as the data is more than likely already on your computer.
Will this work for offline? If someone views a todolist, makes some changes offline, then visits it later online will it sync the changes automatically?
I do plan to add a helper for that, that keeps a list of unsynced models. Then a function could be called when the server is reachable, or just periodically.
We're going to release soon, so in the next few weeks I'm likely to add dirty model syncing.
Now I just need to find (or write) some php code that will save/serve the fetched json model.
There's no specific local querying beyond listing window.localStorage.