Created
March 12, 2012 04:20
-
-
Save akgupta/2019769 to your computer and use it in GitHub Desktop.
Revisions
-
akgupta created this gist
Mar 12, 2012 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,46 @@ // 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); } }