Trigger an action on the change event with Ember.js checkbox input helper?

I'd like to post an update to this. In Ember 1.13.3+, you can use the following:

<input type="checkbox" 
       checked={{isChecked}} 
       onclick={{action "foo" value="target.checked"}} />

link to source


For those using Ember > 2.x:

{{input
  change=(action 'doSomething')
  type='checkbox'}}

and the action:

actions: {
  doSomething() {
    console.warn('Done it!');
  }
}

Post Ember version >= 1.13 see Kori John Roys' answer.

This is for Ember versions before 1.13


This is a bug in ember's {{input type=checkbox}} helper.

see https://github.com/emberjs/ember.js/issues/5433

I like the idea of having a stand-in. @Kingpin2k's solution works, but accessing views globally is deprecated and using observers isn't great.

In the linked github ember issue, rwjblue suggests a component version:

App.BetterCheckboxComponent = Ember.Component.extend({
  attributeBindings: ['type', 'value', 'checked', 'disabled'],
  tagName: 'input',
  type: 'checkbox',
  checked: false,
  disabled: false,

  _updateElementValue: function() {
    this.set('checked', this.$().prop('checked'));
  }.on('didInsertElement'),

  change: function(event){
    this._updateElementValue();
    this.sendAction('action', this.get('value'), this.get('checked'));
  },
});

Example usage in a template ('checked' and 'disabled' are optional):

{{better-checkbox name=model.name checked=model.checked  value=model.value disabled=model.disabled}}

using an observer seems like the easiest way to watch a checkbox changing

Template

{{input type='checkbox' checked=foo}}

Code

  foo:undefined,
  watchFoo: function(){
    console.log('foo changed');
  }.observes('foo')

Example

http://emberjs.jsbin.com/kiyevomo/1/edit

Or you could create your own implementation of the checkbox that sends an action

Custom Checkbox

App.CoolCheck = Ember.Checkbox.extend({
  hookup: function(){
    var action = this.get('action');
    if(action){
      this.on('change', this, this.sendHookup);
    }
  }.on('init'),
  sendHookup: function(ev){
    var action = this.get('action'),
        controller = this.get('controller');
     controller.send(action,  this.$().prop('checked'));
  },
  cleanup: function(){
    this.off('change', this, this.sendHookup);
  }.on('willDestroyElement')
});

Custom View

{{view App.CoolCheck action='cow' checked=foo}}

Example

http://emberjs.jsbin.com/kiyevomo/6/edit

Tags:

Ember.Js