51

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?

bguiz
  • 27,371
  • 47
  • 154
  • 243

1 Answers1

111

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/

Marcio Junior
  • 19,078
  • 4
  • 44
  • 47
  • I was also following an outdated Ember.js tutorial that had an older way of calling methods from an ArrayController. Found this answer after hours of searching and it probably saved me many more hours. Thanks! – TheBrockEllis Apr 27 '14 at 02:07