Skip to content

Commit

Permalink
fix($core): safe useEventListener (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
2nthony authored Sep 13, 2021
1 parent 710fa02 commit 1e63488
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
3 changes: 2 additions & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"./*": "./*"
},
"dependencies": {
"@svelte-use/shared": "0.2.0"
"@svelte-use/shared": "0.2.0",
"@svelte-use/store": "0.2.0"
}
}
11 changes: 5 additions & 6 deletions packages/core/useEventListener/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { onDestroy } from 'svelte'
import { listen } from 'svelte/internal'
import { readable } from 'svelte/store'
import { defaultWindow } from '../_configurable'
import {
Fn,
isString,
noop,
isReadable,
MaybeReadable,
tryOnDestroy,
} from '@svelte-use/shared'
import { readable } from '@svelte-use/store'

interface InferEventTarget<Events> {
addEventListener(event: Events, fn?: any, options?: any): any
Expand Down Expand Up @@ -129,8 +129,8 @@ export function useEventListener(...args: any[]) {

let cleanup = noop

const targetStore = isReadable(target) ? target : readable(target)
const unsubscribe = targetStore.subscribe((el) => {
const store = isReadable(target) ? target : readable(target)
store.subscribe((el) => {
cleanup()

if (!el) {
Expand All @@ -146,11 +146,10 @@ export function useEventListener(...args: any[]) {
})

const stop = () => {
unsubscribe()
cleanup()
}

onDestroy(stop)
tryOnDestroy(stop)

return stop
}

0 comments on commit 1e63488

Please sign in to comment.