EmberJS-Handling User Interaction with Actions



Handling User Interaction with Actions

The {{action}} helper makes elements interactive with components in your web application. In this case, actions are sent inside a component directly to the Ember.Component instance.

Ember.Component.extend({
   actions: {
      //do the stuff
   }
});

In the above code, actions helper is defined directly within the Ember.Component instance.

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Handling User Interaction with Actions</title>
      <!-- CDN's-->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script>
      <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script>
      <script src="https://builds.emberjs.com/release/ember.debug.js"></script>
      <script src="https://builds.emberjs.com/beta/ember-data.js"></script>
   </head>
   <body>
      <script type="text/x-handlebars" data-template-name="index">
         <h1>Click on button to toggle:</h1>
         {{my-comp title="Click Me"}}
      </script>

      <script type="text/x-handlebars" data-template-name="components/my-comp">
         <!-- calling the toggle function -->
         <button {{action "toggleBody"}}>{{title}}</button>
         {{#if isShowing}}
            <h2>Tutorialspoint</h2>
         {{/if}}
      </script>

      <script type="text/javascript">
         App = Ember.Application.create();

         App.MyCompComponent = Ember.Component.extend({
            //action helper for component
            actions: {
               //toggling the text
               toggleBody: function() {
                  this.toggleProperty('isShowing');
               }
            }
         });
      </script>
   </body>
</html>

Output

Let's carry out the following steps to see how above code works −

  • Save above code in comp_action_handlr.htm file

  • Open this HTML file in a browser.

Advertisements