Created
January 30, 2013 13:47
-
-
Save tdd/4673427 to your computer and use it in GitHub Desktop.
Quick run-through of syncing a Backbone.Collection with a localStorage cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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