Ember.js — OnChange file input

Okay, so a couple of weeks ago, I made a post about JavaScript onChange file input and I since I have been working on Ember.js, I thought I would show you guys how to do it in Ember.js for those who are curious.

One reason why you might want to learn how to do it in Ember.js is for unit testing. This was one of the particular reason why I had to learn how to do it in Ember because I could not test the file object in the onChange function.

// sendData.html
<input id=”FileInput”
  type=”file”
  accept=”image/png,image/jpeg”
  onchange={{action send ‘onChangeFile’}}
>

// sendData.js
let onChangeFile() {
  let fileInput = Ember.$(“#clientCardInput”)[0]
  let image = fileInput.files[0]
  this.controller.set(‘model.image’, image)
}

If you have read my post on the JavaScript version, this would look almost identical. The only difference is that we are using the Ember reference to access the DOM, Ember.$, which is an alias to jQuery’s $ because Ember is built upon jQuery.

We are also using our controller to set the image so that our unit test can reference this when we create or render this component. The key thing here is that we set our model data, model.image to the image that we grabbed using Ember.$. If we had done it the JavaScript way, Ember unit test would not have any reference to the model.image and therefore have no way of validating where the file was selected or not.