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:

class App.ModelWithImage extends Batman.Model
  @encode 'imageDataURI'

  constructor: ->
    @observe 'imageFile', (newVal, oldVal) ->
      if newVal?
        @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 =
      @set 'imageDataURI', dataURI

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!