4

I would like my Backbone.js based web app to function offline. Upon detecting offline state, how can I queue up Backbone's sync events so that they're sent to the server after connectivity is restored?

lairtech
  • 2,337
  • 4
  • 25
  • 38
  • have a look at these: http://stackoverflow.com/questions/3285348/offline-online-data-synchronization-design-javascript http://stackoverflow.com/questions/2441973/javascript-library-for-client-side-storage-with-server-side-sync – j03w Aug 12 '13 at 03:32

1 Answers1

1

You can use two Backbone.sync methods and swap them out depending on offline/online state:

// Detect sync however you want here
var state = getInternetConnectivityState();

// Save off a local copy of the default Backbone.sync
var ajaxSync = Backbone.sync;

// Create a new Backbone.sync function that works with local storage. I would suggest
// using store.js as it works x-browser, takes care of JSON serialization and is well  
// supported
var localSync = function(method, model, options) {
    if ('GET' === method) {
        model.set('name', store.get(model.id).name);
    }
    ...
}

Backbone.sync = function() {
    if ('offline' === getInternetConnectivityState()) {
        localSync.call(this, arguments);
    }
    else {
        ajaxSync.call(this, arguments);
    }
}
srquinn
  • 10,134
  • 2
  • 48
  • 54