Best practice of passing actions in component inside component

I am working on passing actions in component inside component. In the general, I am using the method like that

home.hbs:

{{layerOne action1="action1" action2="action2" action3="action3" action4="action4" }} home.js

actions:{
    action1: function () {     
      //do something
    },
    action2: function () {  
      //do something    
    },
    action3: function () {   
      //do something   
    },
    action4: function () {  
      //do something   
    }
}

layerOne.hbs

{{layerTwo action1="action1" action2="action2" action3="action3" action4="action4" }}

layerOne.js

actions:{
    action1: function () {   
      this.sendAction('action1');   
    },
    action2: function () {      
      this.sendAction('action2');   
    },
    action3: function () {   
      this.sendAction('action3');      
    },
    action4: function () {    
      this.sendAction('action4');     
    }
}

layerTwo.hbs

{{#paper-button onClick=(action "action1")}}Action 1{{/paper-button}}
{{#paper-button onClick=(action "action2")}}Action 2{{/paper-button}}
{{#paper-button onClick=(action "action3")}}Action 3{{/paper-button}}
{{#paper-button onClick=(action "action4")}}Action 4{{/paper-button}}

layerTwo.js

actions:{
    action1: function () {   
      this.sendAction('action1');   
    },
    action2: function () {      
      this.sendAction('action2');   
    },
    action3: function () {   
      this.sendAction('action3');      
    },
    action4: function () {    
      this.sendAction('action4');     
    }
}

If I add more actions, I have to config the layers’ js file and hbs file one by one every time. Also the hbs will be very long. eg. {{layerOne action1=“action1” action2=“action2” action3=“action3” action4=“action4” etc…}}

Is there any best practice for this case? Thank you.

Yes, the best way is use closure actions, that way you don’t have to use any sendAction

Have a look at the guides to see details of using closure actions.

You can use closure actions to simplify that a lot. So your layers would look like the following :

// LayerOne.js
actions: {
  action1(some, args) {
    // Do something
  }
  
  action2() {
    // Do something
  }
}

<!-- LayerOne.hbs -->
{{layer-two action1=(action "action1") action2=(action "action2")}}
<!-- LayerTwo.hbs -->
<button {{action action1 "some" args}}></button>
<button {{action action2}}></button>

You can find a really good write ups on closure actions here and here (dockyard).

2 Likes