简体   繁体   English

在灰烬中传递论点

[英]Passing argument on action in Ember

I have three toggle buttons in my "hbs" file. 我的“ hbs”文件中有三个切换按钮。 And I have "options" array in the controller related to this template. 我在与此模板相关的控制器中具有“选项”数组。 I want to update "options" whenever user selected/deselected any of buttons. 每当用户选择/取消选择任何按钮时,我都想更新“选项”。 For example, if button 1 selected and other not - "options" must be [1]. 例如,如果选择了按钮1而未选择其他按钮-“选项”必须为[1]。 If second and third buttons selected and first not - "options" must be [2, 3]. 如果选择了第二个和第三个按钮,而第一个没有-“选项”必须为[2,3]。

And I tried to make this through actions with parameters: 我试图通过带参数的动作来做到这一点:

<button {{action 'toggleOption' name aria-pressed}}
id="first-button" name="1" type="button" class="btn 
option-toggle-button" data-toggle="button" aria-pressed="false"
autocomplete="off">First button</button>

Controller: 控制器:

import Ember from 'ember';

export default Ember.Controller.extend({
    options: [],
    actions: {
        toggleOption(id, selected) {
            var options = this.get("options");

            if (selected) {
                if (options.contains(id))
                    options.push(id);
            } else {
                var index = options.indexOf(id);
                if (index >= 0)
                    options.splice(index, 1);
            }

            this.set("options", options);
        }
    }
});

But "toggleOption" was calling with "undefined" params so I assume that I on a wrong way. 但是“ toggleOption”使用“未定义”参数进行调用,因此我认为我使用了错误的方式。

Question: how can I implement needed logic? 问题:如何实现所需的逻辑? Maybe I need a completely different approach to solve this problem? 也许我需要一种完全不同的方法来解决这个问题?

You can use: 您可以使用:

<button {{action 'toggleOption' "1"}} id="first-button" name="1" type="button" class="btn option-toggle-button" data-toggle="button" aria-pressed="false"autocomplete="off">First button</button>

<button {{action 'toggleOption' "2"}} id="first-button" name="1" type="button" class="btn option-toggle-button" data-toggle="button" aria-pressed="false"autocomplete="off">Second button</button>

where "1" and "2" are the values passed to the controller action. 其中"1" and "2"是传递到控制器操作的值。 Then in the toggleOption action you can do your logic to add/remove value into options array 然后,在toggleOption动作中,您可以执行将值添加/删除到options数组中的逻辑

actions: {
    toggleOption(value) {
        // ...your logic here...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM