Created
March 12, 2012 04:20
-
-
Save akgupta/2019769 to your computer and use it in GitHub Desktop.
Overriding backbone sync to use local storage
This file contains 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
// 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); | |
} | |
} |
@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
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!