EmberJS-Views Sending Events



Description

You can send events to the view's controller by having clickable event on the element which affects state of the application.

Syntax

Ember.View.extend({
   click: function(evt) {
      this.get('controller').send('ClickableEvent', params);
   }
});

Ember.Controller.extend({
   actions: {
      ClickableEvent: function(params){
         //Do your logic
      }
   }
});

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Sending Events</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="logged">
         <h1>Click to send an event</h1>
         {{#view App.LoginButton}}
            <button>Click Here</button>
         {{/view}}
      </script>

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

         App.Router.map(function() {
            this.resource('logged');
         });

         App.LoginButton= Ember.View.extend({
            click: function(evt) {
               //this will pass to the current route
               this.get('controller').send('turnItUp');
            }
         });

         App.Route= Ember.Route.extend({
            //it calls when click event occurs
            events: {
               turnItUp: function(){
                  document.write("<b>Welcome to Tutorialspoint</b>");
               }
            }
         });
      </script>
   </body>
</html>

Output

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

  • Save above code in sending_events.htm file

  • Open this HTML file in a browser.

Advertisements