javascript EmberJS 动作 - 当包裹在 `actions` 中时从另一个动作调用一个动作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18743760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:03:51  来源:igfitidea点击:

EmberJS actions - call one action from another when wrapped within `actions`

javascriptember.jspublish-subscribeember-controllers

提问by bguiz

How do you call one action from another action when wrapped within actionsin an EmberJS controller?

当包裹在actionsEmberJS 控制器中时,如何从另一个动作调用一个动作?

Original code that uses the now deprecated way to define actions:

使用现已弃用的方式定义操作的原始代码:

//app.js
App.IndexController = Ember.ArrayController.extend({
    // properties
    /* ... */

    // actions
    actionFoo: function() {
        /* ... */
        this.actionBar();
    },
    actionBar: function() {
        /* ... */
    }
});

//app.html
<div class="foo" {{action actionFoo this}}>
<div class="bar" {{action actionBar this}}>

However, with EmberJS 1.0.0, we get a deprecation warning, saying that actions must be put within an actions object within the controller, instead of directly within the controller, as above.

然而,在 EmberJS 1.0.0 中,我们收到了一个弃用警告,说动作必须放在控制器内的动作对象中,而不是直接放在控制器中,如上所述。

Updating the code, according to recommendations:

根据建议更新代码:

//app.js
App.IndexController = Ember.ArrayController.extend({
    // properties
    /* ... */

    // actions
    actions: {
        actionFoo: function() {
            /* ... */
            this.actionBar(); //this.actionBar is undefined
            // this.actions.actionBar(); //this.actions is undefined
        },
        actionBar: function() {
            /* ... */
        }
    }
});

//app.html
<div class="foo" {{action actionFoo this}}>
<div class="bar" {{action actionBar this}}>

However, I find that it is not possible for one function defined within actions to call another, as the thisobject appears to no longer be the controller.

但是,我发现在动作中定义的一个函数不可能调用另一个函数,因为该this对象似乎不再是控制器。

How can I go about doing this?

我该怎么做呢?

回答by Marcio Junior

You can use the send(actionName, arguments)method.

您可以使用该send(actionName, arguments)方法。

App.IndexController = Ember.ArrayController.extend({
    actions: {
        actionFoo: function() {
            alert('foo');
            this.send('actionBar');
        },
        actionBar: function() {
            alert('bar');
        }
    }
});

Here is a jsfiddle with this sample http://jsfiddle.net/marciojunior/pxz4y/

这是带有此示例的 jsfiddle http://jsfiddle.net/marciojunior/pxz4y/