7

我在循环中有一个select元素,我想要触发的动作需要有两个参数:select元素的 selected 选项和我们正在循环的项目。我的代码如下所示:

{{#each loopItems as |loopItem|}}
 <select onChange={{action 'fireThis' loopItem target.value }}> 
  {{#each loopItem.subItems as |subItem|}}
    <option value={{subItem.id}}>{{subItem.value}}</option>
  {{/each}}
 </select>
{{/each}}

而我的火这个动作是这样的:

fireThis:function(loopItem, value){
 //Do something here with both. 
 // like loopItem.set('thisProperty', value);
}

因此,在我的特定情况下,子项的数量是动态的,我需要将选定的子项与它当前所在的循环项一起使用。

除非重构为组件(现在,我不能这样做),我如何将多个参数传递给在“onChange”上触发的操作?

我努力了:

<select onChange={{action 'fireThis' value ="loopItem target.value" }}> 
<select onChange={{action 'fireThis' value ="loopItem target.value" }}>
<select onChange={{action 'fireThis' loopItem value="target.value"}}>
<select onChange={{action 'fireThis' value="target.value" loopItem}}>

对于上述所有情况,我在函数中的两个参数都未定义(或导致另一个错误)。唯一有效的是:

<select onChange={{action 'fireThis' value="target.value"}}>

但这只会给我 subItem,而不是 loopItem。

不幸的是,loopItems 是新创建的 Ember 对象,没有任何 ID 参数,所以我也不能给每个选择元素一个唯一的 ID。传递多个参数的能力几乎可以解决我的整个问题。

4

4 回答 4

9

有点晚了,但在这里找到的答案有效: ember 2 parameters in a action of a select menu

对于 OP 的解决方案,您可以像这样包装它:

<select onChange={{action (action 'fireThis' loopItem) value="target.value"}}>

于 2017-08-18T17:33:01.200 回答
1

尝试这个:

<select onChange={{action 'fireThis' loopItem}}>

fireThis:function(loopItem){
 var value = this.$('option:selected').val();
 //Do something here with both. 
 // like loopItem.set('thisProperty', value);
}
于 2016-02-11T19:29:48.677 回答
0

我决定——正如他们所说——硬着头皮把整个东西包装成一个组件。我将每个循环项传递给组件+所有必需的对象以使事情正常工作,然后在组件内部,我使用了 value="target.value"。

我重构的代码现在看起来像这样:

{{#each loopItems as |loopItem|}}
   {{loop-item-component loopItem=loopItem}}
{{/each}}

--

// Loop-item-component

    <select onChange={{action 'fireThis' value='target.value' }}> 
      {{#each loopItem.subItems as |subItem|}}
        <option value={{subItem.id}}>{{subItem.value}}</option>
      {{/each}}
    </select>

然后,在组件中,我放置了动作:

actions:{
 ...
    fireThis:function(value){
      let loopItem = this.get('loopItem');
      // Do something here with both. 
      // like loopItem.set('thisProperty', value);
    }
}

到目前为止,我还无法尝试其他建议的答案,但是一旦我这样做了,我就会在这里发布结果;学习如何将多个参数传递给由 select 元素的选项更改触发的操作仍然很有用。

于 2016-02-11T22:08:34.920 回答
0

如果您需要传递多个参数,那么我建议您不要使用value="target.value". 如果你使用它,它将target.value从第一个参数event对象中获取。

<select onchange={{action 'fireThis' loopItem}}>

firethis行动中,您将在参数中接收loopItemevent反对。

actions:{
 firethis(loopItem,event)
 {
  //let selectedValue= event.tager.value;
 }
}
于 2017-08-18T18:31:59.140 回答