Louis Luk
Louis Luk

Reputation: 303

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.

Upvotes: 0

Views: 1476

Answers (1)

ykaragol
ykaragol

Reputation: 6221

You can use closure actions to pass an action handler from upper layer to lower layer.

There are two different action passing mechanism in ember:

  1. event passing such as {{layerTwo action1="action1". (needs calling sendActions in each component to bubble up.)
  2. closure actions such as {{layerTwo action1=(action "action1") (only needs passing action handler to the bottom.)

This twiddle demonstrates how to use closure actions. You can see there is nothing in js files.

If you use closure actions with quotes such as (action 'action1') then a function in actions hash will be searched and passed to the bottom component.

If you use closure actions without quotes such as (action action1) then a function of that component will be passed to the bottom component. (The function needs to be either defined in that component or passed to that component.)

This is a very good resource to understand closure actions.

Upvotes: 5

Related Questions