Recreating Google Docs automatic "Saving..." status display
= render :partial => 'admin/menu'
.page-header
%h1= t 'form.entry.header.new'
%span.pull-right.label.label-success#update_status_label
%span#save_state= t 'form.update_status.saved'
%time.timeago{datetime: ''}
= form_for @entry, :url => admin_entry_path(@entry), :method => :patch, html: {role: 'form'} do |f|
.form-group
= f.label :title
= f.text_field :title, class: 'form-control'
.form-group
= f.label :body
= f.text_area :body, class: 'form-control'
$(document).ready ->
update_status_label = $('#update_status_label')
update_status_time = $('#update_status_label time.timeago')
update_status_save_state = $('#save_state')
admin.timeago_timeout = [] # array of timeout ids
refresh_timestamp = ->
update_status_label.removeClass('label-info') if update_status_label.hasClass('label-info')
update_status_label.addClass 'label-success'
update_status_save_state.html I18n.t('form.update_status.saved')
update_status_time.attr 'datetime', (new Date()).toISOString()
update_status_time.show()
set_saving_state = ->
# clear every existing timeout counters
for id in admin.timeago_timeout
clearTimeout(id)
admin.timeago_timeout = []
update_status_label.removeClass('label-success') if update_status_label.hasClass('label-success')
update_status_label.addClass 'label-info'
update_status_save_state.html I18n.t('form.update_status.saving')
update_status_time.hide()
# prevent accidental navigations
window.onbeforeunload = ->
I18n.t 'form.ask_user_done_editing'
$('#entry_title').keyup ->
patch_entry {_method: 'patch', title: $(this).val()}
$('#entry_body').keyup ->
patch_entry {_method: 'patch', body: $(this).val()}
patch_entry = (data_to_submit)->
set_saving_state()
$.post(gon.entry_patch_path, data_to_submit)
.done((data)->
console.log data
admin.timeago_timeout.push setTimeout(refresh_timestamp, 1500)
)
.fail((jqXHR, textStatus, errorThrown)->
console.error(textStatus)
console.error(errorThrown)
)
# set initial timestamp
refresh_timestamp()
update_status_time.timeago()