lundi 15 février 2016

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.




Aucun commentaire:

Enregistrer un commentaire