简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM