2
votes

I'm trying to work with a simple overlay component, and close this overlay if someone clicks outside of the overlay content:

<div class="overlay" {{action 'close' on='click'}}>
  <div class="item">
    <form {{action 'submit' on='submit'}}>
      {{yield}}
      {{#link-to closeRoute class="close"}}Close{{/link-to}}
    </form>
  </div>
</div>

The component looks like this:

import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    submit: function() {
      this.sendAction();
    },
    close: function(param) {
      console.log(param); // -> undefined
      console.log(this);  // -> complete component object, no reference to the event?
      // this.$("a.close").click();
    }
  }
});

This works like advertised, however, I need to determine the target of the click event, because also clicks on the item and form will trigger this click(close) action.

Question: How can I access the (jQuery) event object which has a target from within the close action inside the component?

I am using EmberCLI, and Ember 1.9

1
I've seen documentation that the action gets one parameter being the event but that documenation was for views. Although Components are inherited from views it does not seem to pass the event as parameter. - ahmeij

1 Answers

1
votes

I have found this to provide the required result:

export default Ember.Component.extend({
  classNames: ['overlay-block'],
  didInsertElement: function() {
    var self = this;

    self.$().click(function(e) {
      if (self.$(e.target).hasClass("overlay-block")) {
        self.$("a.close").click();
      }
    });
  }
});

This does not use an ember action like I expected. I'll leave the question open for a while to see if somebody comes up with an more 'Ember way' of doing this.

More Ember way

export default Ember.Component.extend({
  classNames: ['overlay-block'],
  click: function(e) {
    if (this.$(e.target).hasClass("overlay-block")){
      this.$("a.close").click();
    }
  }
});