JackH
JackH

Reputation: 4735

What is the right way to listen for clicks outside an Ember Component?

I have an Ember.js component called header-main.js with the template header-main.hbs. Within the Handlebars file, I have something like this:

<ul id="header-nav">
  <li class="unopened">
    <a href="javascript:void(0);">Brand</a>
    <ul class="dropdown">
      <li><a href="javascript:void(0);">Lenovo</a></li>
      <li><a href="javascript:void(0);">Dell</a></li>
      <li><a href="javascript:void(0);">HP</a></li>
    </ul>
  </li>
</ul>

In the component's didInsertElement hook, I have some jQuery that changes the class of the <li> tag to show the dropdown menu like this:

didInsertElement: function() {
    this.$('#header-nav li > a').click(function() {
    var currentState = $(this).parent().attr('class');

    if (class === 'unopened') {
        $(this).parent().attr('class', 'open');
    } else {
        $(this).parent().attr('class', 'unopened');
    }
  });
}

This all works great except, it forces the user to only click the button to toggle the dropdown unlike most websites that let you just click anywhere in the window to close the dropdown. What is the right way to make sure that the dropdown within this component can be closed by clicking anywhere in the window? I also face similar situations with modal windows.

Upvotes: 0

Views: 451

Answers (2)

mattyboy
mattyboy

Reputation: 91

This is very out of date (but it is an old question). To help future engineers looking for an answer, from EmberJS 3.28+ they moved towards using modifiers to handle this and other component events.

Please see the EmberJS 5 Component Docs for details, specifically there is an example on-click-outside which explains how to do this.

Note: In EmberJS 3.x, 4.x you will need to install ember-modifier package to do this. It is fully integrated in EmberJS 5, no additional package required.

Upvotes: 0

Rakesh G R
Rakesh G R

Reputation: 804

Use JQuery focusout() to define the closing action. So whenever the component loses focus,ie.,there is a click outside, it should close.

Upvotes: 2

Related Questions