Ember's checkbox and 'checked' attribute : two-way binding not works?

I do not understand. When I try this code:

my index.hbs :

<input type="checkbox" checked={{cbState}} /> {{cbState}}<br />
{{input type="checkbox" checked=cbState}} {{cbState}}

my controller index.js:

import Ember from 'ember';

export default Ember.Controller.extend({
    cbState: false
});

If i check a checkbox, cbState is always false… Why ? I hope cbState change to true

Thanks for your help.

The first one doesn’t change the value because it is not two way binding, only one way.

The second way works fine.

2 Likes

Thank you,

OK for the first one, i did not realize it was only one way :slight_smile:. Thank you.

The second way works like this but I forgot to mention that I used an action ‘change’ like this:

index.hbs:

{{input type="checkbox" checked=cbState change=(action "myChangeAction")}}

index.js:

import Ember from 'ember';

export default Ember.Controller.extend({
    cbState: false,

    actions: {
        myChangeAction() {
            const state = this.get('cbState'); // cbState is not updated when use 'change' event
            ...
        }
    }
});

myChangeAction is executed, no problem. But cbState does not change now… If i use a click event like this:

{{input type="checkbox" checked=cbState click=(action "myChangeAction")}}

It works again but i need current cbState value in my myChangeAction function and in click event, the cbState value has not yet changed. It’s the previous value :confused:

To show cbState with or without click or change actions : Ember Twiddle

I think the best solution is:

  1. not use ‘change’ event. Use ‘click’ event instead.
  2. and define an Ember.observer on cbState property to execute js code…
1 Like

Ember uses the change method to toggle the checked attribute[ ember.js/checkbox.js at v2.9.1 · emberjs/ember.js · GitHub ]

I think change=(action “myChangeAction”) essentially overwrites it. So, the correct way is probably to toggle the property inside the action:

actions: {
  myChangeAction() {
      this.toggleProperty(cbState);
      // Do your stuff here
  }

Hello,

Thanks for your example.

I tried your example but something is wrong : if we use toggleProperty, OK it works. But if we want to always set cbState to true, your example does not work anymore.

I updated my twiddle (Ember Twiddle) and when we click on last checkbox, its state change whatever the value of cbState :confused:

Yeah, not sure why it behaves the way it does. Looks like using plain HTML input is the recommended way to do this: Input checkbox component does not update the checked property · Issue #14640 · emberjs/ember.js · GitHub

Try this.togglProperty(“cbState”);