Search code examples
ember.jsember-cli

How to get the clicked element on Ember Component


I'm learning EmberJS, I tried to search the docs and stuff but I couldn't get it right so far I've implemented the component and a action to respond on click event, for now it just print something in the console. I want to get the clicked element so I could change it's style and attributes. I'm using the scaffold generated by ember-cli version 0.2.7 Follows the code:

app/components/heart-like.js

import Ember from 'ember';

export default Ember.Component.extend({
  actions:{
    click: function (event) {
      console.log(event); // undefined
      console.log("Hello from component");
    }
  }
});

app/templates/components/heart-like.hbs

 <div class="row">
      <span {{action "click"}} class="pull-right" style="color: #B71C1C;"><i class="fa fa-2x fa-heart"></i></span>
</div>

Solution

  • Ember.EventDispatcher delegates some events to the corresponding Ember.View. Since Ember.Component is a subclass of Ember.View, you can capture click events just exposing a click function:

    export default Ember.Component.extend({   
      click: function (event) {
        console.log(event.target); // displays the clicked element
        console.log("Hello from component");
      }
    });
    

    Keep in mind that using directly these event hooks isn't a good practice because you're dealing directly with the DOM, and not expressing your intention. Depending of your use case it's a better alternative to just create a property in the component and change it via actions. For instance, to change the color of the icon when it's clicked:

    component

    export default Ember.Component.extend({
      color: 'red',
      actions:{
        changeColor: function() {
          this.set('color', 'black');
        }
      }
    });
    

    template

      <div class="row">
          <span {{action "changeColor"}} class="pull-right" style="color: {{color}};"><i class="fa fa-2x fa-heart"></i></span>
      </div>
    

    Live demo