Implementing image preview is breeze thanks to batman.js observers and JavaScript APIs.
The goal is to have a user add an image to a file input and immediately preview that image. To accomplish this, we’ll turn the uploaded file into a data URI, then set that to the src
of our <img/>
.
First, set up the observer in the model:
class App.ModelWithImage extends Batman.Model
@encode 'imageDataURI'
constructor: ->
super
@observe 'imageFile', (newVal, oldVal) ->
if newVal?
@_setImageDataURIFromFile()
else
@set 'imageDataURI', ""
This says: “whenever imageFile
changes, if there is a new value, use it to set the data URI, otherwise, set the data URI to ""
.”
Now, implement _setImageDataURIFromFile
:
_setImageDataURIFromFile: ->
file = @get('imageFile')
reader = new FileReader
reader.onload = (e) =>
dataURI = e.target.result
@set 'imageDataURI', dataURI
reader.readAsDataURL(file)
You can use it in a template like this:
<img data-bind-src='component.imageDataURI' />
<input type='file' data-bind='component.imageFile' />
When a user uploads a file, the <img>
will be automatically updated!