Last active
December 16, 2015 22:30
-
-
Save rikukissa/5507850 to your computer and use it in GitHub Desktop.
iframe-fileupload binding handler for knockout
This file contains 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
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