How to click button from ember.js controller?

by mallory_cormier , in category: Javascript , a month ago

How to click button from ember.js controller?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , a month ago

@mallory_cormier 

In Ember.js, you can trigger a click event on a button element from a controller by using the action helper and the click() method. Here's a step-by-step guide on how to do this:

  1. In your template file (e.g., app/templates/my-template.hbs), add a button element with an action attribute that will trigger a function in your controller when clicked:
1
<button {{action "handleButtonClick"}}>Click Me</button>


  1. In your controller file (e.g., app/controllers/my-controller.js), define the action function that will be called when the button is clicked:
1
2
3
4
5
6
7
8
9
import Controller from '@ember/controller';

export default Controller.extend({
  actions: {
    handleButtonClick() {
      // Perform any logic you need here
    }
  }
});


  1. To programmatically click the button from your controller, you can use the following code snippet inside the handleButtonClick function:
1
2
3
4
5
handleButtonClick() {
  Ember.run.next(() => {
    this.$('button').click();
  });
}


In this code snippet, we use Ember.run.next() to ensure that the DOM has been updated before triggering the click event on the button element. We then use jQuery to select the button element and call the click() method on it.


By following these steps, you can easily click a button from an Ember.js controller.