Skip to content

Instantly share code, notes, and snippets.

@akgupta
Created March 12, 2012 04:20
Show Gist options
  • Select an option

  • Save akgupta/2019769 to your computer and use it in GitHub Desktop.

Select an option

Save akgupta/2019769 to your computer and use it in GitHub Desktop.

Revisions

  1. akgupta created this gist Mar 12, 2012.
    46 changes: 46 additions & 0 deletions localStorageSync.js
    Original 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);
    }
    }