Simple data synchronisation for PhoneGap applications and Web Application using LocalStorage

Demonstration of data synchronisation for PhoneGap applications and Web Application using LocalStorage. backbone, backbone-localstorage, data synchronization, offline data sync, phonegap app

by bharatpatil

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.5.3/jquery.mockjax.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script src="http://jashkenas.github.io/backbone/backbone.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.1.7/backbone.localStorage-min.js"></script>

JavaScript

//clear first time local storage
window.localStorage.clear();

//mock ajax request
$.mockjax({
  url: '/restful/data',
  method: 'POST',
  responseTime: 10,
  responseText: {
    status: 'success', 
  }
});

var self, // this is used to preserve reference to SyncQueue instance
    QUEUE_NAME = 'ServerSyncQueue'; // this is used by backbone localStorage to identify collection

function setSelf(that) {
  self = that;
}

//queue data model- this should be nothing but options required by $.ajax refer http://api.jquery.com/jquery.ajax/ 
var QueueModel = Backbone.Model.extend({
  defaults:{
    'url': null,
    'method': null //http method
  }
});

//sync queue
var SyncQueue = Backbone.Collection.extend({
  
  model: QueueModel,
  
  currentModel: null, 
  
  timeOutVar: null,
  
  localStorage: new Backbone.LocalStorage(QUEUE_NAME),
  
  initialize: function() {
    setSelf(this);
  },
  
  setSyncTimer: function(milliSeconds) {
    milliSeconds = typeof milliSeconds !== 'undefined' ? milliSeconds : 5000;
    if(self.timeOutVar) { clearTimeout(self.timeOutVar); }
    setTimeout(self.startSync, milliSeconds);
  },
  
  //add model into queue 
  enqueue: function (model) {
    self.localStorage.create(model);
    self.setSyncTimer(1000);
    
  },  

  //when syncing is done
  syncSuccess: function () {
    self.localStorage.destroy(self.currentModel);
    self.currentModel = null;
    self.setSyncTimer(1000);
  },
  
  //when error occurred while syncing
  syncError: function () {
    self.currentModel = null;
    setTimeout(self.startSync, 1000);
  },
  
  //sync init method
  startSync: function () {
    console.log('startSync '+ 'models length: ' + self.models.length);
    self.localStorage = new Backbone.LocalStorage(QUEUE_NAME);
    self.fetch();   
    if (self.models.length > 0 && self.currentModel === null) {
      self.currentModel = self.models[0];
      self.send();
    }
  },
  
  send: function() {   
    var ajaxJSON = self.currentModel.toJSON();
   ...