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.
https://ember-twiddle.com/e1ecffd40037fde5b3dc?openFiles=templates.application.hbs%2C
2 Likes
Thank you,
OK for the first one, i did not realize it was only one way . 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
To show cbState
with or without click
or change
actions : https://ember-twiddle.com/d7581365d4c370e3c9d35d13da9e47be?openFiles=templates.application.hbs%2C
I think the best solution is:
not use ‘change’ event. Use ‘click’ event instead.
and define an Ember.observer
on cbState
property to execute js code…
1 Like
Ember uses the change method to toggle the checked attribute[ https://github.com/emberjs/ember.js/blob/v2.9.1/packages/ember-htmlbars/lib/components/checkbox.js#L64 ]
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
}
Myrdhin
November 27, 2016, 10:41am
#6
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 (https://ember-twiddle.com/d7581365d4c370e3c9d35d13da9e47be ) and when we click on last checkbox, its state change whatever the value of cbState
Yeah, not sure why it behaves the way it does. Looks like using plain HTML input is the recommended way to do this: https://github.com/emberjs/ember.js/issues/14640
cgallo
January 31, 2019, 8:12pm
#8
Try this.togglProperty(“cbState”);