Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8eb0b2d

Browse files
feat(onLongClick): return stop function (#3506)
Co-authored-by: lee <[email protected]>
1 parent 9b0141c commit 8eb0b2d

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

packages/core/onLongPress/index.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,29 @@ describe('onLongPress', () => {
8787
expect(onParentLongPressCallback).toHaveBeenCalledTimes(0)
8888
}
8989

90+
async function stopEventListeners(isRef: boolean) {
91+
const onLongPressCallback = vi.fn()
92+
const stop = onLongPress(isRef ? element : element.value, onLongPressCallback, { modifiers: { stop: true } })
93+
94+
// before calling stop, the callback should be called
95+
element.value.dispatchEvent(pointerdownEvent)
96+
97+
await promiseTimeout(500)
98+
99+
expect(onLongPressCallback).toHaveBeenCalledTimes(1)
100+
101+
stop()
102+
103+
// before calling stop, the callback should no longer be called
104+
onLongPressCallback.mockClear()
105+
106+
element.value.dispatchEvent(pointerdownEvent)
107+
108+
await promiseTimeout(500)
109+
110+
expect(onLongPressCallback).toHaveBeenCalledTimes(0)
111+
}
112+
90113
function suites(isRef: boolean) {
91114
describe('given no options', () => {
92115
it('should trigger longpress after 500ms', () => triggerCallback(isRef))
@@ -97,6 +120,7 @@ describe('onLongPress', () => {
97120
it('should not tirgger longpress when child element on longpress', () => notTriggerCallbackOnChildLongPress(isRef))
98121
it('should work with once and prevent modifiers', () => workOnceAndPreventModifiers(isRef))
99122
it('should stop propagation', () => stopPropagation(isRef))
123+
it('should remove event listeners after being stopped', () => stopEventListeners(isRef))
100124
})
101125
}
102126

packages/core/onLongPress/index.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { Fn } from '@vueuse/shared'
12
import { computed } from 'vue-demi'
23
import type { MaybeElementRef } from '../unrefElement'
34
import { unrefElement } from '../unrefElement'
@@ -63,6 +64,12 @@ export function onLongPress(
6364
once: options?.modifiers?.once,
6465
}
6566

66-
useEventListener(elementRef, 'pointerdown', onDown, listenerOptions)
67-
useEventListener(elementRef, ['pointerup', 'pointerleave'], clear, listenerOptions)
67+
const cleanup = [
68+
useEventListener(elementRef, 'pointerdown', onDown, listenerOptions),
69+
useEventListener(elementRef, ['pointerup', 'pointerleave'], clear, listenerOptions),
70+
].filter(Boolean) as Fn[]
71+
72+
const stop = () => cleanup.forEach(fn => fn())
73+
74+
return stop
6875
}

0 commit comments

Comments
 (0)