There is some confusion around views and components in Ember. Early on when getting into Ember, I too found it confusing. I’ve gone back-and-forth in my usage of Ember views vs. components in the applications that I work on.
Views are great because they don’t care much about interactions beyond the typical
doubleClick, etc. events.
Components buy you all of that, plus they enforce some strict encapsulation which helps keep code bases from
spaghettifying rapidly. The encapsulation is good, but becomes cumbersome when you have a big, parent component that encapsulates a lot of behavior.
Note: The approach in this blog post will likely become moot in Ember 2.0 with the introduction of routable components.
Thus, you might find yourself with a component that looks similar to the following:
The actions here are merely being passed through to the controller, which in this example is the top-most logical object that encapsulates the business logic for these actions. (Several different things on the page, for example, could start editing the mode in this fictional blogging system.) Although the explicitness is nice, this just becomes yet-another-thing-to-update.
Instead, we can work around this problem by having the component actions directly call the actions on the controller. We can do this in a way that doesn’t introduce unnecessary coupling:
And in the controller:
Then, the template that instantiates this component becomes a lot cleaner:
The downside to this approach is minor: it’s no longer easy to see which events a component emits when looking at the template that instantiates it.
So, that’s a quick strategy toward reducing the “action cruft” in your templates when using components. If you think this is terrible idea, or have a better solution: send me an email.
Special thanks to Nuck, locks, and yaymukund, from #emberjs on Freenode for giving this a once-over before it went live.