Last Updated: February 25, 2016
·
4.939K
· tomkr

Ember Actions, Routes and Controllers

I've been working with Ember for about a week now, and I'm really liking it so far. There is a lot to learn, but I've been figuring things out at a steady pace.

One of the things that might not be intuitive at first is the way [Routes] and [Controllers] work. If you're coming from Rails, an Ember Route does a lot more than a Rails Route, and that might take some getting used to. Especially once you start mixing in Actions, which don't really have a place in server-side web development.

Actions are a simple way to turn a JavaScript event (generally a click) into a method you can execute. Both Routes and Controllers can handle an Action, but the more common place to do this in my experience is a Route, which would not have been my first guess. The Ember documentation has this image to clarify how this works.

Ember actions

As you can see, an Action goes to the Controller of the current Route, then to the current Route itself and afterwards it bubbles up through all of its parents. This means if you handle an Action in a Route, you have much more control over where it is handled. This allows you to target exactly the right Route easily.

Controllers in Ember are best seen as a wrapper around the Model that is currently being displayed. It is a good place to store state about the UI or model that does not need to be sent back to the server. But if a click somewhere should affect something out of the scope its own Template, it is easiest to handle this Action in the corresponding Route, and set something on its Controller with:

self.get('controller').set('controllerField', 'value');

In summary:

  • Actions: an easy way to turn an event into a function call
  • Controllers: a wrapper around your model and a good place to store the state of dynamic UI elements
  • Route: the easiest place to handle Actions, by handling them in the right place

1 Response
Add your response

Heya Tom,

Great tip! It was a life savor that I stumbled on your post. And to add up, I want to point out a scenario I ran into, and moving actions from controller to route did the trick:

I've got a route/controller, which is using dynamicly rendered templates, based on the transition coming from. I have an action, which when finished, had to transitionToRoute to another route. On first load of the route's views, the action finishes fine and transitioned properly. But when I again open this view and hit the action (on this.transitionToRoute('route')), I got a 'Cannot use transitionToRoute on undefined'. Weird thing is that 'this' context was passed ok, but seems to be lost in the way.

After moving the action to the route, the transitionTo is now going as expected.

Cheers and thanks,
Nickey

over 1 year ago ·