Best practises of Closure Actions in Ember

This blog will help to avoid use of sendAction() in favour of closure actions. Let us try and understand how sendAction() and send() actions work in ember .

What is sendAction() and send() in ember?
sendAction() is the way to call action on a parent scope from the respective component. And send() is used to call action within the same controller of a controller or a component.

Why to avoid use of the sendAction()?
Since Ember (from version >1.13) works in the Function Down Action Up way. Function can be passed to deeply nested components in the hierarchy from the parent scope without not much use of sendAction().
Using sendAction() makes your code tightly coupled and can also cause create a syntactic issues which means not passing the function properly can make your application break

To understand sendAction() and send() better here is an example to it

In the example above there is a controller which has a parent component to it and parent component has a child component inherited to it. So whenever a button present in the child component is clicked then the action ClickMe() of the controller should be called.

All the actions are passed in the template(.hbs) file and actions are called in the respective controllers .

The example mentioned shows that how actions of components are dependent on each other because of sendAction().

That implies if action of any components/controllers present in the hierarchy breaks it might affect the actions of the components/controllers down in their hierarchy.

Here the use of Closure functions will help to reduce the clumsiness and dependency of sendAction() used in the above example.

PS: The @ sign used above is used to indicate that the action is passed from controller and not component

In the above example, the functions using sendAction() has been removed and all the actions of the dependent components are passed through the templates in the form of closure functions

So when the button ClickMe() is clicked the action is now referenced to the action in the demo controller instead of the parent component as seen in the previous example.

The workflow still remains the same but inside of passing the actions the reference of the action are passed with the help of closure actions.

The use of closure action has reduced the dependency and made actions of the controller and components less coupled.

References:
https://axiomq.com/blog/introduction-to-ember-closure-actions
https://spin.atomicobject.com/2016/06/25/emberjs-closure-actions/
https://guides.emberjs.com/v3.1.0/components/triggering-changes-with-actions/

Please do let me know your suggestions or comments for the same.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store