resolves #47 Co-authored-by: johba <johba@harb.eth> Reviewed-on: https://codeberg.org/johba/harb/pulls/54
25 lines
886 B
TypeScript
25 lines
886 B
TypeScript
import type { DirectiveBinding } from 'vue';
|
|
|
|
interface ClickOutsideElement extends HTMLElement {
|
|
clickOutsideEvent?: (event: MouseEvent) => void;
|
|
}
|
|
|
|
export default {
|
|
beforeMount(el: ClickOutsideElement, binding: DirectiveBinding<(event: MouseEvent) => void>) {
|
|
el.clickOutsideEvent = function (event: MouseEvent) {
|
|
// Check if the clicked element is neither the element
|
|
// to which the directive is applied nor its child
|
|
if (!(el === event.target || el.contains(event.target as Node))) {
|
|
// Invoke the provided method
|
|
binding.value(event);
|
|
}
|
|
};
|
|
document.addEventListener('click', el.clickOutsideEvent);
|
|
},
|
|
unmounted(el: ClickOutsideElement) {
|
|
// Remove the event listener when the bound element is unmounted
|
|
if (el.clickOutsideEvent) {
|
|
document.removeEventListener('click', el.clickOutsideEvent);
|
|
}
|
|
},
|
|
};
|