Skip to content

Instantly share code, notes, and snippets.

@ianhenrysmith
Created February 8, 2013 16:46
Show Gist options
  • Select an option

  • Save ianhenrysmith/4740243 to your computer and use it in GitHub Desktop.

Select an option

Save ianhenrysmith/4740243 to your computer and use it in GitHub Desktop.
Autosaving form in Coffeescript
# form should have class 'autoupdate' and should have data-remote set to true
$(".autoupdate input").live("paste keyup change blur", () ->
@$this = @$this || $(this)
@$form = @$form || @$this.closest("form")
@val = @$this.val()
unless @val == @old_val
@old_val = @val
queue_save(@$form)
)
queue_save = ($form) ->
if $form.data("set_up") != true
setup_form($form)
unless $form.data("save_queued") == true
$form.data("save_queued", true)
$form.find('.form_status').text("Unsaved")
save = () -> update_form($form)
window.setTimeout(save, 5000) #save queued
setup_form = ($form) ->
$form.data("set_up", true)
$form.append("<p class='form_status text_smaller'></p>")
# prevent blarphing
# should also handle timeouts etc
# should move this to its own method
$form.bind('ajax:complete', (e) ->
e.preventDefault()
set_text = () -> $form.find('.form_status').text("Saved")
window.setTimeout(set_text, 1000)
)
update_form = ($form) ->
$form.data("save_queued", false)
$form.find('.form_status').text("Updating")
$form.submit()
@ianhenrysmith
Copy link
Author

this queueing thing could probably be taken out and make into its own module

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