Skip to content

Commit

Permalink
!feat: changed how useEventListener works to allow for options
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon Milfred committed Jan 12, 2024
1 parent a46a4fc commit 3667306
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions composables/useEventListener.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,34 @@
import { onMounted, onBeforeUnmount, isRef } from 'vue';

export function useEventListener(...args) {
let [targets, event, callback, immediate] = [
let [targets, event, callback, options] = [
typeof args[1] === 'string' ? args.shift() : undefined,
...args,
];

// Make sure we are working with an options object
options =
typeof options === 'boolean'
? { capture: options }
: typeof options === 'object'
? { ...options }
: {};
const { immediate } = options;
delete options.immediate;

onMounted(() => {
setTimeout(() => {
targets = resolveTargets(targets);
targets?.forEach((target) =>
target.addEventListener(event, callback)
target.addEventListener(event, callback, options)
);
immediate && callback();
});
});

onBeforeUnmount(() => {
targets?.forEach((target) =>
target.removeEventListener(event, callback)
target.removeEventListener(event, callback, !!options?.capture)
);
});
}
Expand Down

0 comments on commit 3667306

Please sign in to comment.