Skip to content

Commit

Permalink
feat(watchOnce): return function for manual watcher stopping (#3475)
Browse files Browse the repository at this point in the history
  • Loading branch information
valerypatorius committed Nov 9, 2023
1 parent f9136e8 commit bb0a78e
Showing 1 changed file with 6 additions and 4 deletions.
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
}

0 comments on commit bb0a78e

Please sign in to comment.