Actions are important to controllers. They are triggered by the user action and can be used to change the application state. In this recipe, we'll create four different types of actions and see how they react to different situations.
$ ember g controller application $ ember g route application
We'll be using the controller
and application
to store actions. Some actions will bubble up to the route
, and some won't.
// app/controllers/application.js import Ember from 'ember'; export default Ember.Controller.extend({ actions: { action1(){ alert('Application controller action action1'); }, action2(){ alert('Application controller action action2'); return true; }, action3(val){ alert(`Value Passed: ${val}`); } } });
Let's take a look at each action:
action1(){ alert('Application controller action action1'); },
This is a normal action. It just displays an alert box:
action2(){ alert('Application controller action action2'); return true; },
This action is a little more interesting. By default, all controller actions return false
if they exist in the controller. By returning the value to true
, this action will bubble up to the application
route after the alert box is displayed. The route can then handle the action:
action3(val){ alert(`Value Passed: ${val}`); }
The action has a value passed to it. It will display this value to the user in an alert box. The text in the alert box is using something called ES6 template strings. This makes it a little easier to display variables in text.
// app/routes/application.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { enter(){ alert('Application route action enter!'); }, action2(){ alert('Application route action action2!'); } } });
Each action displays an alert box. You might have noticed that the enter
action was not present in the controller. By convention, template actions
will look first in the controller. If the action is not defined in the controller, it will bubble up to the route.
// app/templates/application.hbs <h2 id="title">Welcome to Ember</h2> <button {{action 'action1'}}>Action 1 in controller</button> <button {{action 'action2'}}>Action 2 in controller and route</button> <button {{action 'action3' 'Hello World'}}>Action 3 Passing Values</button> <button {{action 'enter'}}>Action enter only in route</button>
Each button
has an action
bound to it. By default, this is bound to the click event; this can be changed if needed.
ember server
. Open a web browser to see the following screen:This displays a message from the controller.
This second alert box is displayed from the application route.
This shows the message from the controller with the value passed.
This will show the message from the application route as it was not defined in the controller.