How to get Ember to detect a checkbox on change along with a glimmer tracked?

257 Views Asked by At

In ember js version 3.2.6, how do we get a checkbox to do extra logic on value changed?

Example, I have a checkbox (a toggle true/false) for updateServer. The existing code is using a glimmer @tracked and this work fine for showing some instant UI modification as can be seen on the application.hbs.

Value of update server:
{{updateServer}} 

But then I need to add some logic on value change, see onCheckboxChange. That function is called, but it seem the value of updateServer is not the one after click. It's the older one, before click. See picture.

How do I get the latest value of updateServer?

The value of update server is not the latest ones

application.js

import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class ApplicationController extends Controller {
  @tracked updateServer = false;

  @action
  onCheckboxChange() {
    //some extra logic
    console.log(`at controller, updateServer is: ${this.updateServer}`);
  }
}

application.hbs

{{page-title 'EmberSimple'}}

<label>
  <Input @type='checkbox' @checked={{this.updateServer}} {{on 'change' onCheckboxChange}}/>
  Update Server</label>
<br />
Value of update server:
{{updateServer}}
<br />
{{outlet}}
1

There are 1 best solutions below

2
On BEST ANSWER

One simple solution is to just not use <Input but a primitive <input. This could look like this:

<input type="checkbox" checked={{this.updateServer}} {{on "click" this.onCheckboxChange}} />

However then you manually need to assign the new value to the tracked property:

@action
onCheckboxChange(event) {
  this.updateServer = event.target.checked;
  console.log(`at controller, updateServer is: ${this.updateServer}`);
}