如何将多个参数传递给Ember2.3中select元素的onChange操作

时间:2016-02-11 19:13:30

标签: ember.js ember-2.0.0

我在循环中有一个 select 元素,我想要触发的动作需要有两个参数:选择元素的选定选项和项目我们正在循环。我的代码看起来像这样:

{{#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 操作如下:

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

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

除非重构为组件(现在,我不能这样做),如何将多个参数传递给在'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 Objects,没有任何ID参数,所以我也不能给每个select元素一个唯一的ID。传递多个参数的能力几乎可以解决我的整个问题。

4 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分: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);
}

答案 2 :(得分:0)

我决定 - 他们说 - 咬紧牙关并将整个东西包裹成一个组件。我将每个loopitem传递给组件+所有必需的对象以使其工作,然后在组件内部,我使用value =&#34; target.value&#34;。

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

{{#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元素选项的更改触发的动作仍然有用。

答案 3 :(得分:0)

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

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

并在firethis操作中,您将在参数中收到loopItemevent个对象。

actions:{
 firethis(loopItem,event)
 {
  //let selectedValue= event.tager.value;
 }
}