Ember hbs 模板是否应该将参数从输入字段传递给函数,如果是,如何传递?

Should the Ember hbs template pass in parameters from an input field to a function and if so how?

我有一个表单,它有一个输入字段和一个关联的按钮,我有一个函数想要将用户键入的值输入到输入字段中。我应该以某种方式从 hbs 模板传递它,还是应该直接从函数中的 DOM 获取它。

有这样的吗?

{{ action myFunction $("#myInputId").val() }}

是的,您可以通过 actionvalue 属性 来执行此操作,如下所示:

<input oninput={{action "myaction" value="target.value"}}/>

这是给你的ember-twiddle

您可以将输入框的值绑定到控制器 属性,然后您可以使用该控制器 属性 来导出按钮操作中输入框的值。

这是给你的ember-twiddle

注意:Ember控制器是SINGLETONS

无法直接传递值,但可以将值绑定到 属性。 我建议将输入包装在组件中并将输入值绑定到组件 属性。 然后您可以将该值作为操作参数传递或直接在组件的操作处理程序中访问它。 此解决方案避免了单例控制器,并且该组件可能会被重用。

另见 https://guides.emberjs.com/v2.18.0/templates/actions and https://guides.emberjs.com/v2.18.0/templates/input-helpers

从概念上讲 - 您走在正确的轨道上。

在这种情况下...这是一条路线(申请路线)

import Ember from 'ember';

export default Ember.Route.extend({

  alertInput: function(inputValue) {
    alert(inputValue);
  },

  actions: {
    doSomething(userInput) { // (this is already a function)
    // alert(userInput); // or... use a regular function in the action
      this.get('alertInput')(userInput);
    },
  },

});

这是一个模板(申请模板)

{{input value=userInputProperty}}

<button {{action 'doSomething' userInputProperty}}>doSomething</button>

此操作采用一个函数名称 - 然后是一个值作为传递给该函数的参数。

根据您要执行的操作,您可以采用几种方法。

https://ember-twiddle.com/3080649ecf98cddef6d3d64b186ba741?openFiles=templates.application.hbs%2C (玩转的好时机)