Diederik
Diederik

Reputation: 612

Ember close responsive menu

I am having troubles with closing my responsive menu in Ember. Currently I have a menu icon, if someone presses this, the following action fires:

export default Ember.Controller.extend({
    actions: {
        openMenu() {
            $('#menu').toggle();
        }
    }
});

Which naturally opens my menu. However, when someone presses a link (regardless of where on the page this is) I obviously want the menu to close again. I am finding it difficult how to perform this.

Basically what I want is this:

$('a').click(function() {
    $('#menu').hide();
});

But I simply do not know where to place this code.

I have thought about adding a new helper which mimics the Ember linkTo helper, but I am sure that this would not be the correct solution to the problem. Or is it?

Disclaimer: I am really new to Ember. I use version 2.2 and I do know that they're phasing out controllers, I am working on that too ;).

Upvotes: 1

Views: 248

Answers (2)

RZKY
RZKY

Reputation: 300

A more graceful solution would be to listen to click event on the component itself.

export default Ember.Component.extend({
  actions: {
    openMenu() {
      this.$('#menu').toggle();
    }
  },

  // use Ember's built in click handler
  // https://guides.emberjs.com/v2.1.0/components/handling-events/
  click(event) {
    // check if the link is clicked
    if (event.target.tagName.toLowerCase() === 'a') {
      this.$('#menu').hide();
    }
  }
});

Upvotes: 1

TheCompiler
TheCompiler

Reputation: 308

Given that Ember is phasing out controllers, you should put your openMenu action in the route instead. You can add the hide event to the didTransition hook in the same route.

//route-name.js
import Ember from 'ember';

export default Ember.Route.extend({
  actions: {

    didTransition: function() {
      Ember.$('a').click(function() {
        Ember.$('#menu').hide();
      });
    },

    openMenu: function() {
      Ember.$('#menu').toggle();
    }

  }
})

Upvotes: 1

Related Questions