Created
June 20, 2012 15:45
-
-
Save rubysolo/2960575 to your computer and use it in GitHub Desktop.
use localStorage to store form datas
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 characters
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 |
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
Okay, I went ahead and made this into a plugin: https://github.com/rubysolo/jquery-safetynet