wip: watcher cleanup improvement

This commit is contained in:
Evan You 2019-06-06 13:25:05 +08:00
parent e5e56bb358
commit 1d41771e56
3 changed files with 13 additions and 2 deletions

View File

@ -11,6 +11,7 @@ export interface ReactiveEffect {
scheduler?: Scheduler scheduler?: Scheduler
onTrack?: Debugger onTrack?: Debugger
onTrigger?: Debugger onTrigger?: Debugger
onStop?: () => void
} }
export interface ReactiveEffectOptions { export interface ReactiveEffectOptions {
@ -19,6 +20,7 @@ export interface ReactiveEffectOptions {
scheduler?: Scheduler scheduler?: Scheduler
onTrack?: Debugger onTrack?: Debugger
onTrigger?: Debugger onTrigger?: Debugger
onStop?: () => void
} }
export type Scheduler = (run: () => any) => void export type Scheduler = (run: () => any) => void
@ -49,6 +51,7 @@ export function createReactiveEffect(
effect.scheduler = options.scheduler effect.scheduler = options.scheduler
effect.onTrack = options.onTrack effect.onTrack = options.onTrack
effect.onTrigger = options.onTrigger effect.onTrigger = options.onTrigger
effect.onStop = options.onStop
effect.computed = options.computed effect.computed = options.computed
effect.deps = [] effect.deps = []
return effect return effect

View File

@ -134,6 +134,9 @@ export function effect(
export function stop(effect: ReactiveEffect) { export function stop(effect: ReactiveEffect) {
if (effect.active) { if (effect.active) {
cleanup(effect) cleanup(effect)
if (effect.onStop) {
effect.onStop()
}
effect.active = false effect.active = false
} }
} }

View File

@ -83,10 +83,15 @@ export function watch<T>(
const newValue = runner() const newValue = runner()
if (options.deep || newValue !== oldValue) { if (options.deep || newValue !== oldValue) {
try { try {
if (isFunction(cleanup)) { // cleanup before running cb again
if (cleanup) {
cleanup() cleanup()
} }
cleanup = cb(newValue, oldValue) const _cleanup = cb(newValue, oldValue)
if (isFunction(_cleanup)) {
// save cleanup so it is also called when effect is stopped
cleanup = runner.onStop = _cleanup
}
} catch (e) { } catch (e) {
// TODO handle error // TODO handle error
// handleError(e, instance, ErrorTypes.WATCH_CALLBACK) // handleError(e, instance, ErrorTypes.WATCH_CALLBACK)