Listening to the Escape Key with ember-keyboard in a Classic Class

Last reviewed on December 19, 2020

Recently I was helping someone make all modals in an application close when a user presses the escape key. Thankfully, ember-keyboard makes it very easy to listen to key events, like pressing the escape key.

The application we were working on has A LOT of modals that all extend from a base component class, so I figured it'd be best to add the listener code to that base class in order to touch as few files as possible.

If you look at the ember-keyboard docs, most of the examples are using native class syntax with decorators. The base class that we wanted to add this feature to was using an Ember classic class, and I didn't want to convert the classic class to a native class just yet, as that might introduce a regression.

So, here is how to use ember-keyboard to listen to when the escape key is pressed in a classic class:

import Component from '@ember/component';
import { keyResponder, onKey } from 'ember-keyboard';

export default keyResponder(
  Component.extend({
    closeOnEscape: onKey('Escape', function () {
      console.log('closing...');
    }),
  })
);

keyResponder and onKey are decorators and can be used in a classic class as shown above and in a native class as shown below:

import Component from '@glimmer/component';
import { keyResponder, onKey } from 'ember-keyboard';

@keyResponder
export default class BaseModal extends Component {
  @onKey('Escape')
  closeOnEscape() {
    console.log('closing...');
  }
}

The string value for the escape key is "Escape", which you can find in this list of keyboard code values. The ember-keyboard docs do link to this but it can be easy to miss.

It took me roughly 20 minutes to figure out how to listen to the pressing of the escape key in a classic class, so hopefully this saves you a little bit of time if you're looking to do the same thing.