Skip to content

Instantly share code, notes, and snippets.

@rubysolo
Created June 20, 2012 15:45
Show Gist options
  • Save rubysolo/2960575 to your computer and use it in GitHub Desktop.
Save rubysolo/2960575 to your computer and use it in GitHub Desktop.
use localStorage to store form datas
class OfflineBackup
constructor: ->
@pendingRequests = JSON.parse(localStorage.getItem('offline-backups') || '[]')
$('form.offline-backup').on 'submit', @submitForm
window.addEventListener 'online', @submitPendingRequests
submitForm: (e) ->
unless navigator.onLine
method = $(this).find('input[name=_method]').val() || $(this).attr('method') || 'get'
key = "#{ $(this).attr('action') }:#{ method }:#{ new Date().getTime() }"
value = $(this).serialize()
backupManager.addPendingRequest(key, value)
e.preventDefault()
addPendingRequest: (key, value) ->
localStorage.setItem(key, value)
backupManager.pendingRequests.push(key)
localStorage.setItem('offline-backups', JSON.stringify(backupManager.pendingRequests))
submitPendingRequests: ->
if request = backupManager.pendingRequests[0]
data = localStorage.getItem(request)
[ action, method ] = request.split(':')
$.ajax
type: method
url: action
data: data
success: =>
backupManager.pendingRequests.shift()
localStorage.setItem('offline-backups', JSON.stringify(backupManager.pendingRequests))
localStorage.removeItem(request)
backupManager.submitPendingRequests()
$ -> window.backupManager = new OfflineBackup
@jwreagor
Copy link

My two cents but moar jQuery... $("[data-offline-backup=true]").offlineBackup() would be clearer, bringing out the selector from the implementation, not tying it to a style class and not requiring direct instantiation. Otherwise I love it.

@rubysolo
Copy link
Author

rubysolo commented Jun 20, 2012 via email

@rubysolo
Copy link
Author

Okay, I went ahead and made this into a plugin: https://github.com/rubysolo/jquery-safetynet

@jwreagor
Copy link

I love it. Definitely going to be using this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment