Robert Mosolgo

To my knowledge, batman.js is not maintained. For that reason, I don't suggest that you use it for a new project!

Client-Side Image Preview With Batman.js

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:

1
2
3
4
5
6
7
8
9
10
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:

1
2
3
4
5
6
7
  _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:

1
2
  <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!