-
-
Save cliftonscott/d06bdf76612ed9484ad844befdfca182 to your computer and use it in GitHub Desktop.
Vue 3 directive with Typescript - focusChangeNotify
This file contains hidden or 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 { DirectiveBinding, ObjectDirective } from 'vue' | |
| type FocusableElement = HTMLInputElement | HTMLTextAreaElement | |
| type NotificationCallback = (isNowFocused: boolean) => void | |
| type GenericEventHandler = () => void | |
| interface ExtendedDirective extends ObjectDirective { | |
| handleFocus: GenericEventHandler | |
| handleBlur: GenericEventHandler | |
| } | |
| const focusChangeNotify = { | |
| handleFocus: (() => {}) as GenericEventHandler, | |
| handleBlur: (() => {}) as GenericEventHandler, | |
| mounted(element: FocusableElement, binding: DirectiveBinding) { | |
| const callback = (binding.value as NotificationCallback) | |
| const thisDirective = binding.dir as ExtendedDirective | |
| thisDirective.handleFocus = () => { callback(true) } | |
| thisDirective.handleBlur = () => { callback(false) } | |
| element.addEventListener('focus', thisDirective.handleFocus) | |
| element.addEventListener('blur', thisDirective.handleBlur) | |
| }, | |
| beforeUnmount(element: FocusableElement, binding: DirectiveBinding) { | |
| const thisDirective = binding.dir as ExtendedDirective | |
| element.removeEventListener('focus', thisDirective.handleFocus) | |
| element.removeEventListener('blur', thisDirective.handleBlur) | |
| } | |
| } | |
| export default focusChangeNotify |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment