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 |
Good call, I'll work on that. Thanks!
…On Wed, Jun 20, 2012 at 9:59 AM, Justin Reagor < ***@***.*** > wrote:
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.
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/2960575
Okay, I went ahead and made this into a plugin: https://github.com/rubysolo/jquery-safetynet
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
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.