Skip to content

Commit

Permalink
Merge pull request #386 from PrefectHQ/enhancement/update-useEventLis…
Browse files Browse the repository at this point in the history
…tener-to-accept-window
  • Loading branch information
dylanbhughes authored Feb 2, 2024
2 parents 7ef2053 + d7430b7 commit f3b6702
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/useEventListener/useEventListener.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,5 +132,22 @@ describe('useEventListener', () => {
expect(updatedAddEventListenerMock).not.toHaveBeenCalled()
})

it('also functions with window as the target', () => {
const callback = vi.fn()
const addEventListenerMock = vi.spyOn(window, 'addEventListener')

const { remove } = useEventListener(window, 'click', callback)

fireEvent.click(window)
expect(callback).toHaveBeenCalledOnce()
expect(addEventListenerMock).toHaveBeenCalledOnce()

remove()

fireEvent.click(window)

expect(callback).toHaveBeenCalledOnce()
})

})

3 changes: 2 additions & 1 deletion src/useEventListener/useEventListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ const defaultOptions: UseEventListenerOptions = {

export function useEventListener<K extends keyof DocumentEventMap>(target: MaybeRefOrGetter<Document | undefined | null>, key: K, callback: (this: Document, event: DocumentEventMap[K]) => unknown, options?: UseEventListenerOptions): UseEventListener
export function useEventListener<K extends keyof HTMLElementEventMap>(target: MaybeRefOrGetter<HTMLElement | undefined | null>, key: K, callback: (this: HTMLElement, event: HTMLElementEventMap[K]) => unknown, options?: UseEventListenerOptions): UseEventListener
export function useEventListener<K extends keyof WindowEventMap>(target: MaybeRefOrGetter<Window | undefined | null>, key: K, callback: (this: Window, event: WindowEventMap[K]) => unknown, options?: UseEventListenerOptions): UseEventListener
// eslint-disable-next-line max-params
export function useEventListener<K extends string>(target: MaybeRefOrGetter<Node | undefined | null>, key: K, callback: (this: Node, event: Event) => unknown, options: UseEventListenerOptions = {}): UseEventListener {
export function useEventListener<K extends string>(target: MaybeRefOrGetter<Window | Node | undefined | null>, key: K, callback: (this: Node | Window, event: Event) => unknown, options: UseEventListenerOptions = {}): UseEventListener {
const { immediate, ...listenerOptions } = { ...defaultOptions, ...options }
const manualMode = ref(!immediate)

Expand Down

0 comments on commit f3b6702

Please sign in to comment.