Where to write actions?

I’ll just admit: I’m not always entirely sure where to put actions.

When I started with Ember, I put all actions in the controller. Then after reading a thread on here (*will find link), it seemed most actions were best placed in the route, particularly model actions. Maybe with state actions remaining in the controller. Maybe some actions even spread over both… …

I find some actions seem more appropriate in the controller. Especially with things moving more to components. If an action is passed to a component, then it needs to be passed via the controller, so why not write it there?

So, my question is, thinking further ahead to routable components, is this something I can look forward to not having to worry about?!

Opinion is split on this within the Ember community. The official stance (one we reflect in the guides) is that because routable components are still being designed, trying to skate toward where the puck is going could be an exercise in frustration. The upgrade path from controllers to routable components may also be smoother (though no promises there :smiley:)

I continue to use controllers and don’t route actions to my routes …

3 Likes

Add actions on your routes like this:

https://github.com/broerse/ember-cli-blog/blob/master/app/routes/posts.js#L16

I’m keeping actions in controllers for now, it’s still the “current” approach that you will see in add-ons, guides, etc. If/when controllers do become obsolete there will be a clear migration path which will bring much less pain (in my opinion) than trying to put actions on routes when that is not how the core Ember code works.

Well, actually I take a very different approach. I view the routes as just entry points to different views, then in each view I have a hierarchy of components, the rule is that only top-level components are allowed to use services every thing else is DDAU. The top-level components access services that provide data, this in itself provides ample possibilities to isolate data operations to the service layer, something that I find helps with debugging since I can guarantee that no data manipulation is happening outside of the services. The top level components do all the required interaction with the services. I believe that this will be a model that also fits well once controllers are gone and routable components are in.

This SO thread is a bit old but still relevant: ember.js - Ember defining actions, in controller vs in route - Stack Overflow

I think the reason to have it route is because route have access to the controller, but controller don’t have access to the route. So you can do more things with action handlers on the route.