Skip to content

Instantly share code, notes, and snippets.

@sagalbot
Last active June 16, 2020 15:11
Show Gist options
  • Save sagalbot/6eb4c5ab18114bd2cd2def4836f791cf to your computer and use it in GitHub Desktop.
Save sagalbot/6eb4c5ab18114bd2cd2def4836f791cf to your computer and use it in GitHub Desktop.
Modal Escape Hanlding
// in setup() ..
// bind listeners on mount/unmount
useEscapeKeydownWhenMounted(() => {
emit('close');
});
// bind listeners based on condition
useEscapeKeydownWhen(toRef(props, 'open'), () => {
emit('close');
});
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));
}
@sagalbot
Copy link
Author

Not crazy about the naming of onAfterEscapeKeydown. Maybe handlerFactory?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment