Skip to content

Instantly share code, notes, and snippets.

@thbar
Created May 20, 2012 20:06
Show Gist options
  • Save thbar/2759379 to your computer and use it in GitHub Desktop.
Save thbar/2759379 to your computer and use it in GitHub Desktop.
Handling server-side round-trip acknowledgement with KnockOut.js
@status_change_pending = ko.observable(false)
@paid = ko.computed({
owner: @
read: () =>
@status() == 'paid'
write: (value) =>
oldVal = @status() # keep track to handle failure
newVal = if value == true then 'paid' else 'to_be_paid'
@status(newVal)
@status_change_pending(true) # mark as disabled first
$.ajax({
type: 'PUT'
url: "/entries/#{@id()}"
dataType: 'json'
data: { status: newVal }
error: (response) =>
@status(oldVal)
alert("An error occurred!")
complete: () =>
@status_change_pending(false)
})
})
<input type="checkbox" data-bind="checked: paid, disable: status_change_pending" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment