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

▼魔方 西西 提交于 2019-12-03 06:28:36

问题


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

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.

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 this object appears to no longer be the controller.

How can I go about doing this?


回答1:


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

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/



来源:https://stackoverflow.com/questions/18743760/emberjs-actions-call-one-action-from-another-when-wrapped-within-actions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!