Search code examples
javascriptember.jsember-cli

Ember.js assign action to a component inside component's js file


I have a bootstrap button group which is dynamically created. So I created a button component which has a different icon and text.

For now I have assigned the action to the span inside the button.

sample-component.js

export default Ember.Component.extend({
  tagName: 'button',
  actions:{
    triggerStatus:function(){
        this.sendAction('triggerStatus',this.get('dataId'),this.get('type'));
    }
  },
  didInsertElement: function(){
    //is it possible to assign action here
  }
 }

sample-component.hbs

<span class="glyphicon glyphicon-{{icon}}" aria-hidden="true" {{action "triggerStatus"}}></span>

I tried this.set('action','triggerStatus') inside didInsertElement but it didn't work out. Can someone suggest me how to assign a action to a component within the javascript file itself? Is it possible to do so?


Solution

  • Finally found the solution for the problem. The solution was very simple just we can add a click handler inside the component and from there we can invoke sendAction method. Please find the example code snippet below

    export default Ember.Component.extend({
      tagName: 'button',
      //rewrite the following action to
      /*actions:{
        triggerStatus:function(){
          this.sendAction('triggerStatus',this.get('dataId'),this.get('type'));
        }
      }*/,
      //to a component click handler
      click: function(){
        this.sendAction('triggerStatus',this.get('dataId'),this.get('type'));
      }
    }
    

    and removed the action from the span tag in the sample-component.hbs file

    <span class="glyphicon glyphicon-{{icon}}" aria-hidden="true"></span>
    

    Now each button in the button group have the different action based on the type