我有一个像这样的复选框:
{{input type="checkbox" checked=property}}
当我单击复选框时,属性已更改。现在我想调用一个函数来保存属性。但是最好的方法是什么?
{{input ... input=(action "actionName") click=(action "actionName")}}
这不起作用,因为在调用操作时该属性仍具有旧值。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 表明它是可行的覆盖。model.get('hasDirtyAttributes')
。 [更新]在我的测试用例中,操作被调用两次,但在我的实际代码中,它只被调用一次,所以这似乎是最好的解决方案?[/ Update]那么什么是正确的ember.js方式呢?
我个人更喜欢单向绑定复选框。我像这样使用原生的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以及template和component js如何实现灵感,如果您想要一个比本机更好看的复选框
看看我的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