EmberJS actions - 当包装在“actions”中时,从另一个操作调用一个操作

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

本文关键字:操作 actions 调用 另一个 一个 包装 中时 EmberJS      更新时间:2023-09-26

当包装在 EmberJS 控制器中的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}}>

但是,在 EmberJS 1.0.0 中,我们会收到弃用警告,指出操作必须放在控制器内的 actions 对象中,而不是如上所述直接放在控制器中。

根据建议更新代码:

//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}}>

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

我该怎么做呢?

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

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

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