余烬-将事件和其他参数传递给动作处理程序



在我的Ember组件中,我有一个字符串列表,以及一个在列表的特定索引处更新字符串的函数。

animals: computed(function() {
return ["dog", "cat"];
}),
updateAnimal(value, index) {
this.animals[index] = value;
},

在我的hbs中,我在#each循环中将字符串列表呈现为文本字段。当我focus-out文本字段时,我想在特定索引处更新字符串。

{{#each animals as |animal index|}}
<textarea
value={{animal}}
{{on "focusout" (action updateAnimal value="details.value")}}
/>
{{/each}}

但是如何将索引传递给处理程序呢?换句话说,我如何同时传递事件和一些额外的参数?非常感谢你回答我的问题!!

您可以使用{{fn}}帮助器将参数应用于操作:

{{#each this.animals as |animal|}}
<textarea {{on "focusout" (fn this.updateValue animal)}} />
{{/each}}

updateValue方法将接收animal作为第一个参数,事件作为第二个参数。

import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class MyComponent extends Component {
animals = ['dog', 'cat'];
@action
updateAnimal(animal, event) {
const { value } = event.target;
window.alert(`Changed text for animal ${animal} to ${value}`);
}
}

请查看这个Ember Twiddle运行的代码:https://ember-twiddle.com/cad87d51ec2e1fdfd88b8a123ba2d7dd?openFiles=components.my-component%5C.js%2Ctemplates.components.my-component%5C.hbs

请注意,我使用烬辛烷值原语现代化了你的代码。我使用了原生类,放弃了计算属性以支持类字段,避免了模板中的隐式this回退,并使用@action装饰器绑定this上下文。它应该与你问题中使用的旧模式相似。但是我认为新的辛烷原语更容易理解。

最新更新