Skip to content

Instantly share code, notes, and snippets.

@rikukissa
Last active December 16, 2015 22:30
Show Gist options
  • Save rikukissa/5507850 to your computer and use it in GitHub Desktop.
Save rikukissa/5507850 to your computer and use it in GitHub Desktop.
iframe-fileupload binding handler for knockout
ko.bindingHandlers.fileupload =
init: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) ->
el = $(element).find('input')
el.on 'change', (e) =>
form = $('<form class="file-upload" target="_iframe" method="post" action="TARGET_URL" enctype="multipart/form-data"></form>')
frame = $('<iframe name="_iframe">')
frame.appendTo el.parent()
el.wrap form
frame.load ->
frame.off 'load'
err = null
try
data = $.parseJSON(frame.contents().text())
catch e
err = e
el.unwrap()
form.remove()
frame.remove()
valueAccessor().apply(viewModel, [err, data])
el.parent().on('submit', (e) ->
e.stopPropagation()
).submit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment