Skip to content

Instantly share code, notes, and snippets.

@akgupta
Created March 12, 2012 04:20
Show Gist options
  • Save akgupta/2019769 to your computer and use it in GitHub Desktop.
Save akgupta/2019769 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);
}
}
@rahmathm1
Copy link

pelase add read me documentation.

@headwinds
Copy link

You could just link to the article: http://engineering.linkedin.com/mobile/linkedin-ipad-using-local-storage-snappy-mobile-apps which is a great write up!

@joshbedo
Copy link

joshbedo commented May 2, 2014

@akgupta I'm not sure how this overrides Backbone.sync by just adding sync, are you directly editing the Backbone.js sync method?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment