EmberJS actions - call one action from another when wrapped within `actions`
Javascriptember.jsPublish SubscribeEmber ControllersJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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/