什么是适当的ember.js方式来对更改的复选框做出反应

问题描述 投票:0回答:2

我有一个像这样的复选框:

{{input type="checkbox" checked=property}}

当我单击复选框时,属性已更改。现在我想调用一个函数来保存属性。但是最好的方法是什么?

  1. 我可以将观察者绑定到属性but this is consindered bad.
  2. 我可以绑定一个动作来输入oder点击。 {{input ... input=(action "actionName") click=(action "actionName")}} 这不起作用,因为在调用操作时该属性仍具有旧值。
  3. 扩展类Checkbox: import Checkbox from '@ember/component/checkbox'; Checkbox.reopen({ onChange: null, change() { this._super(); if (this.onChange) this.onChange(); } }); ... {{input ... onChange=(action "actionName")}} 但功能改变is not documented,即使the source code 表明它是可行的覆盖。
  4. 我可以将操作绑定到didUpdate或didUpdateAttrs,但操作会被调用两次。在我的情况下,这不会是一个问题,因为属性是模型的一部分,所以我可以在动作中调用model.get('hasDirtyAttributes')。 [更新]在我的测试用例中,操作被调用两次,但在我的实际代码中,它只被调用一次,所以这似乎是最好的解决方案?[/ Update]

那么什么是正确的ember.js方式呢?

checkbox ember.js
2个回答
2
投票

我个人更喜欢单向绑定复选框。我像这样使用原生的input

<input type="checkbox" checked={{myValue}} onclick={{action (mut myValue) value="target.checked"}}>

检查这个twiddle,看看它是否生效。对于单向绑定复选框,这是最简单的非库方法,我认为它是2.x的“余烬方式”(虽然我知道仍然喜欢并使用双向绑定输入的人更多需要观察者,就像我所描述的那样。

在我的一个项目中,我使用ember-paper,它使用了一个没有input的精美显示的复选框,我相信a11y的正确咏叹调绑定。他们利用click来调用onChange

click() {
    if (!this.get('disabled')) {
      invokeAction(this, 'onChange', !this.get('value'));
    }
    // Prevent bubbling, if specified. If undefined, the event will bubble.
    return this.get('bubbles');
}

这样你就可以使用以下api

{{#paper-checkbox value=value1 onChange=(action (mut value1))}}
    A checkbox: {{value1}}
{{/paper-checkbox}}

您可以看到example以及templatecomponent js如何实现灵感,如果您想要一个比本机更好看的复选框


0
投票

看看我的ember-twiddle示例。

我建议使用input帮手,

({input type="checkbox" click=(action "setProperty") checked=my_property}}

切换操作中的属性

setProperty() {
  // toggle the property on click
  this.toggleProperty("my_property");
  console.log(this.get('my_property')); // returns true or false based on the checked value
  .. // do whatever stuff you want
}

如果您在最新版本的ember 3.9中,请查看this

© www.soinside.com 2019 - 2024. All rights reserved.