簡體   English   中英

Ember - 將事件和其他參數傳遞給動作處理程序

[英]Ember - Pass Event and Other Parameter to Action Handler

在我的 Ember 組件中,我有一個字符串列表和一個 function ,它在列表的某個索引處更新字符串。

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}}幫助器將 arguments 應用於操作:

{{#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 原語對您的代碼進行了現代化改造。 我使用本機類,放棄計算屬性或 class 字段,避免在模板中隱含this回退並使用@action裝飾器來綁定this上下文。 它應該與您問題中使用的舊模式類似。 但我認為新的 Octane 原語更容易理解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM