Skip to content

Instantly share code, notes, and snippets.

@tdd
Created January 30, 2013 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdd/4673427 to your computer and use it in GitHub Desktop.
Save tdd/4673427 to your computer and use it in GitHub Desktop.
Quick run-through of syncing a Backbone.Collection with a localStorage cache
// Assumes http://brian.io/lawnchair/ and http://backbonejs.org/
var collection = new MyCollection();
var localStore = new Lawnchair({ name: 'my-cache' }, $.noop);
// First load from the cache, then fetch
function initialLoad() {
localStore.all(function(items) {
collection.reset(items, function() {
collection.fetch();
});
});
}
collection.on('reset', function() {
localStore.nuke(function() {
localStore.batch(collection.toJSON());
});
});
collection.on('add', function(model) {
model.set('key', model.get('some-non-id-field-usable-as-pkey')); // Date.now() does nicely in demos
localStore.save(model.toJSON());
});
collection.on('sync', function(model) {
localStore.save(model.toJSON());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment