In ember.js we can easily pass the properties from parent to child component and can use that property in child component. In this blog, we will see how we can call the parent component action from child component. To call parent action from child component, first we need to pass the parent’s action to child component in the same way we pass other properties.This is possible since actions are simply functions, just like any other method on a component, and they can therefore be passed from one component to another like this:
1 2 3 4 5 6 7 8 9 10 11 |
// app/components/parent-component.js import Ember from 'ember'; export default Ember.Component.extend({ actions: { parentAction() { // perform some task here } } }); |
1 2 3 4 5 |
// app/templates/components/parent-component.hbs {{child-component text="Click here to call parentAction." onConfirm=(action "parentAction") }} |
In the above code, the parent’s component action “parentAction()” is passed to the child component just like we pass properties. The “parentAction()” is available in the child component as the property “onConfiirm”.
Now, we can use “onConfirm
” in the child component to invoke the action on the parent:
1 2 3 4 5 6 7 8 9 10 11 |
// app/components/child-component.js import Ember from 'ember'; export default Ember.Component.extend({ actions: { childAction() { //call the onConfirm property to invoke the parent component action this.get('onConfirm')(); } } }); |
In the above snippet, “
this.get('onConfirm')"
will return the function passed from the parent as the value of “onConfirm"
, and the following “()
” will invoke the parent’s component function. Like normal attributes, actions can be a property on the component; the only difference is that the property is set to a function that knows how to trigger behavior.
Thanks…
What if the parent action receives parameters? Should you give it during the
(action "parentAction" x)
or during the actual call inside the child actionthis.get('onConfirm')(x)
?