Last active
June 16, 2020 15:11
-
-
Save sagalbot/6eb4c5ab18114bd2cd2def4836f791cf to your computer and use it in GitHub Desktop.
Modal Escape Hanlding
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
// in setup() .. | |
// bind listeners on mount/unmount | |
useEscapeKeydownWhenMounted(() => { | |
emit('close'); | |
}); | |
// bind listeners based on condition | |
useEscapeKeydownWhen(toRef(props, 'open'), () => { | |
emit('close'); | |
}); |
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
import { onMounted, onUnmounted, watch } from 'vue'; | |
export const onAfterEscapeKeydown = (callback) => (e) => { | |
if (e.key !== 'Escape') { | |
return; | |
} | |
callback(e); | |
}; | |
export const addEscapeEventKeydownListener = (handler) => | |
document.addEventListener('keydown', handler); | |
export const removeEscapeEventKeydownListener = (handler) => | |
document.removeEventListener('keydown', handler); | |
export function useEscapeKeydownWhen (condition, callback) { | |
const handler = onAfterEscapeKeydown(callback); | |
watch(condition, (condition) => condition | |
? addEscapeEventKeydownListener(handler) | |
: removeEscapeEventKeydownListener(handler)); | |
onUnmounted(() => removeEscapeEventKeydownListener(handler)); | |
} | |
export function useEscapeKeydownWhenMounted (callback) { | |
const handler = onAfterEscapeKeydown(callback); | |
onMounted(() => addEscapeEventKeydownListener(handler)); | |
onUnmounted(() => removeEscapeEventKeydownListener(handler)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not crazy about the naming of
onAfterEscapeKeydown
. MaybehandlerFactory
?