Skip to content

Instantly share code, notes, and snippets.

@bmorrall
Last active November 26, 2022 04:34
Show Gist options
  • Save bmorrall/bb68f1f39bc5c893849c158ef3ea08a9 to your computer and use it in GitHub Desktop.
Save bmorrall/bb68f1f39bc5c893849c158ef3ea08a9 to your computer and use it in GitHub Desktop.
Register a Stimulus Controller to listen to any escape key presses.
// Usage:
//
// import { Controller } from 'stimulus'
// import { useEscapePressed } from './mixins/use-escape-pressed.js
//
// export default class extends Controller {
// connect () {
// useEscapePressed(this)
// }
//
// escapePressed () {
// // close modal/dialog, etc
// }
// }
//
export const useEscapePressed = (composableController) => {
const controller = composableController
const KEYCODE_ESCAPE = 27
const keydownHandler = (event) => {
if (event.key === 'Escape' || event.keyCode === KEYCODE_ESCAPE) {
controller.escapePressed(event)
}
}
const controllerDisconnect = controller.disconnect.bind(controller)
const observe = () => {
document.addEventListener('keydown', keydownHandler, false)
}
const unobserve = () => {
document.removeEventListener('keydown', keydownHandler, false)
}
Object.assign(controller, {
disconnect() {
unobserve()
controllerDisconnect()
}
})
observe()
return [observe, unobserve]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment