Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(watchOnce): return function for manual watcher stopping #3475

Merged
merged 1 commit into from Nov 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 6 additions & 4 deletions packages/shared/watchOnce/index.ts
@@ -1,21 +1,23 @@
import type { WatchCallback, WatchOptions, WatchSource } from 'vue-demi'
import type { WatchCallback, WatchOptions, WatchSource, WatchStopHandle } from 'vue-demi'
import { nextTick, watch } from 'vue-demi'
import type { MapOldSources, MapSources } from '../utils'

// overloads
export function watchOnce<T extends Readonly<WatchSource<unknown>[]>, Immediate extends Readonly<boolean> = false>(source: [...T], cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>, options?: WatchOptions<Immediate>): void
export function watchOnce<T extends Readonly<WatchSource<unknown>[]>, Immediate extends Readonly<boolean> = false>(source: [...T], cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>, options?: WatchOptions<Immediate>): WatchStopHandle

export function watchOnce<T, Immediate extends Readonly<boolean> = false>(sources: WatchSource<T>, cb: WatchCallback<T, Immediate extends true ? T | undefined : T>, options?: WatchOptions<Immediate>): void
export function watchOnce<T, Immediate extends Readonly<boolean> = false>(sources: WatchSource<T>, cb: WatchCallback<T, Immediate extends true ? T | undefined : T>, options?: WatchOptions<Immediate>): WatchStopHandle

// implementation
export function watchOnce<Immediate extends Readonly<boolean> = false>(
source: any,
cb: any,
options?: WatchOptions<Immediate>,
): void {
): WatchStopHandle {
const stop = watch(source, (...args) => {
nextTick(() => stop())

return cb(...args)
}, options)

return stop
}