Now, there's a different way to handle actions on components. Let's generate a new component called ember generate component x-alert.
Here, we can say x-alert here. What we can do is go to application.js. We're going to define an action called doAlert, and going to say window.alert. "Hey, I was clicked." Save.
Notice here nothing is rendering. Let's go to our x-alert.hps template file. What we're going to do here is find a button with a label called alert and save. Now, we'll see the button rendering in our browser.
We're going to go back to our application.hps file. We're going to pass into this x-alert component an attribute called handleClick. Instead of using traditional curly braces, we're going to use an open parenthesis and then say action. We're going to say that the action is doAlert, and then save.
Now, if we go back to our x-alert.hps component, we can now attach this action to a button, but there's a caveat here. When we define this action, we're going to say handleClick, and there's no double quotes like we would if we defined a component-level action. Now, we're going to save.
Now, what happens if we click on this? Oh, wow, we got an alert. What this is is an example of data down, actions up via closure actions. You can define these actions in a parent-level context, such as an application controller, and pass it down to components that can then call it and act accordingly.
Let's tweak our doAlert function to take in a message. We're going to default to, "Hey, I was clicked," if it's undefined via ES6, and rather than sending out the inaudible string, we're going to do window.alert message.
Now, what we're going to do next is go back to application.hps. We're going to say message=yo yo yo into our x-alert component. We're going to go to x-alert.hps and we're going to pass in message to this button action and save.
Now, if we click on this, what you see now is that it's taking this message and displaying it, which is pretty dope. It's like sending that data down, and then using that action, it's sending that data back up, but it's data within the context of this specific component instance.
If we go back and take away that message input, we'll see that we get that default message. Let's add that back in again and go back to application.hps. Let's do a second instance of this component and say doAlert. We're going to say message is, "This is the second one."
We can see if we click on the first one, still have that same message, and other one has the second message.
It's a pretty cool and powerful concept for working with components. Closure actions are nice because they can be extended to do more things, like modifying a property on a controller while also sending up information from a component.
That was closure actions.