Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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