Ember - 将事件和其他参数传递给操作处理程序

Ember - Pass Event and Other Parameter to Action Handler

在我的 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}} helper:

将参数应用于操作
{{#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

请注意,我使用 Ember Octane 基元对您的代码进行了现代化改造。我使用原生 classes,放弃计算 属性 以支持或 class 字段,避免在模板中隐式 this 回退并使用 @action 装饰器绑定 this 语境。它应该与您问题中使用的旧模式类似。但我认为新的 Octane 基元更容易理解。