【问题标题】:EmberJS actions - call one action from another when wrapped within `actions`EmberJS 动作 - 当包装在“动作”中时从另一个动作调用一个动作
【发布时间】:2013-09-15 15:06:24
【问题描述】:

当包装在 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 中,我们会收到一个弃用警告,说必须将动作放在控制器内的动作对象中,而不是像上面那样直接放在控制器中。

根据建议更新代码:

//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 对象似乎不再是控制器。

我该怎么做?

【问题讨论】:

    标签: javascript ember.js publish-subscribe ember-controllers


    【解决方案1】:

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

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

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

    【讨论】:

    • 我还关注了一个过时的 Ember.js 教程,该教程具有从 ArrayController 调用方法的旧方式。经过数小时的搜索后找到了这个答案,它可能为我节省了更多的时间。谢谢!
    猜你喜欢
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2023-03-24
    • 2018-04-18
    相关资源
    最近更新 更多