简体   繁体   中英

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

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 ?

update server 的值不是最新的

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}}

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}`);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM