Last active
November 26, 2022 04:34
-
-
Save bmorrall/bb68f1f39bc5c893849c158ef3ea08a9 to your computer and use it in GitHub Desktop.
Register a Stimulus Controller to listen to any escape key presses.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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