Skip to content

Instantly share code, notes, and snippets.

@paulgosnell
Forked from akgupta/localStorageSync.js
Created May 3, 2012 08:23
Show Gist options
  • Save paulgosnell/2584331 to your computer and use it in GitHub Desktop.
Save paulgosnell/2584331 to your computer and use it in GitHub Desktop.
Overriding backbone sync to use local storage
// overriding sync to use local storage when possible
sync : function(method, model, options){
var key, now, timestamp, refresh;
if(method === 'read' && this.constants.isStoredInLocalStorage) {
// only override sync if it is a fetch('read') request
key = this.getKey();
if(key) {
now = new Date().getTime();
timestamp = $storage.get(key + ":timestamp");
refresh = options.forceRefresh;
if(refresh || !timestamp || ((now - timestamp) > this.constants.maxRefresh)) {
// make a network request and store result in local storage
var success = options.success;
options.success = function(resp, status, xhr) {
// check if this is an add request in which case append to local storage data instead of replace
if(options.add && resp.values) {
// clone the response
var newData = JSON.parse(JSON.stringify(resp));
// append values
var prevData = $storage.get(key);
newData.values = prevData.values.concat(resp.values);
// store new data in local storage
$storage.set(key, newData);
} else {
// store resp in local storage
$storage.set(key, resp);
}
var now = new Date().getTime();
$storage.set(key + ":timestamp", now);
success(resp, status, xhr);
};
// call normal backbone sync
Backbone.sync(method, model, options);
} else {
// provide data from local storage instead of a network call
var data = $storage.get(key);
// simulate a normal async network call
setTimeout(function(){
options.success(data, 'success', null);
}, 0);
}
}
} else {
Backbone.sync(method, model, options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment