在Ember2.3中,如何为select元素的onChange操作传递多个参数

jaql4c8m  于 2023-08-04  发布在  其他
关注(0)|答案(5)|浏览(102)

我在一个循环中有一个select元素,我想触发的动作需要有两个参数:* *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}}

字符串
而我的fireThisaction是这样的:

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


因此,在我的特定情况下,子项的数量是动态的,我需要使用选定的子项和它当前所在的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"}}>


但这只给我子项,而不是循环项。
不幸的是,loopItem是新创建的Ember对象,没有任何ID参数,所以我也不能给予每个select元素一个唯一的ID。传递多个参数的能力几乎可以解决我的整个问题。

z3yyvxxp

z3yyvxxp1#

有点晚了,但在这里找到的答案是有效的:ember 2 parameters in a action of a select menu的数据。
对于OP的解决方案,您可以这样 Package 它:
第一个月

h5qlskok

h5qlskok2#

试试这个:

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

fireThis:function(loopItem){
 var value = this.$('option:selected').val();
 //Do something here with both. 
 // like loopItem.set('thisProperty', value);
}

字符串

moiiocjp

moiiocjp3#

我决定--就像他们说的--咬紧牙关,把整个东西 Package 成一个组件。我将每个循环项传递到组件+所有必需的对象中,然后在组件内部使用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);
    }
}


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

6ju8rftf

6ju8rftf4#

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

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

字符串
firethis action中,您将在参数中接收loopItemevent对象。

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

huus2vyu

huus2vyu5#

您可以像这样在模板中添加第二个参数。

<PowerSelect
    @selected={{this.selectedPrice}}
    @options={{this.priceRange}}
    @onChange={{fn this.choosePrice "minPrice"}}
    class="w-64"
    as |price|
  >
    {{price.title}}
  </PowerSelect>

字符串
然后创建你的函数来处理点击:

@action
  choosePrice(type, price) {
    // type will be 'minPrice'
    // price will be the option you selected
  }

相关问题