I wrote a simple class that substitutes all file inputs in an HTML for a more complex template and set some actions on it. The code is rather small, but I'm not used to write JavaScript.
I wonder if there is a design pattern or extensively used way to set the callbacks? Of course, overall improvements are welcome as well.
The full code is here:
$(document).ready ->
$('input[type="file"]').each ->
new PhotoInput(this)
class PhotoInput
constructor: (originalInput) ->
@renderTemplate(originalInput)
@setClickActions()
@setPreviewRender()
renderTemplate: (originalInput) ->
@template = ich.image_file_input_template # this is ICanHazJS call - it loads a mustache template there.
fileInput: $(originalInput)[0].outerHTML
@fileInput = @template.find('input[type=file]').first()
@previewImage = @template.find('.file-input-preview img')
$(originalInput).replaceWith(@template)
setClickActions: ->
@template.find('#select-file').click =>
@fileInput.focus().click()
@template.find('.file-input-preview').click =>
@fileInput.focus().click()
setPreviewRender: ->
@fileInput.change =>
@previewImage.attr('alt', @fileInput.val())
if(@fileInput[0].files && @fileInput[0].files[0])
reader = new FileReader()
reader.onload = (e) =>
@previewImage.attr('src', e.target.result)
reader.readAsDataURL(@fileInput[0].files[0])