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(effectScope): add onDispose method #10826

Open
wants to merge 7 commits into
base: minor
Choose a base branch
from
11 changes: 11 additions & 0 deletions packages/reactivity/__tests__/effectScope.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,4 +322,15 @@ describe('reactivity/effect/scope', () => {
scope.resume()
expect(fnSpy).toHaveBeenCalledTimes(3)
})

it('should register a cleanup function to be called when the effect scope is stopped', () => {
const spy = vi.fn()

const scope = effectScope()
scope.onDispose(spy)

expect(spy).toHaveBeenCalledTimes(0)
scope.stop()
expect(spy).toHaveBeenCalledTimes(1)
})
})
11 changes: 10 additions & 1 deletion packages/reactivity/src/effectScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,15 @@
this._active = false
}
}

/**
* Registers a cleanup function to be called when the effect scope is stopped.
*
* @param {() => void} fn - The cleanup function to be registered.
*/
onDispose(fn: () => void) {

Check failure on line 149 in packages/reactivity/src/effectScope.ts

View workflow job for this annotation

GitHub Actions / continuous-release

Method must have an explicit return type annotation with --isolatedDeclarations.

Check failure on line 149 in packages/reactivity/src/effectScope.ts

View workflow job for this annotation

GitHub Actions / test / lint-and-test-dts

Method must have an explicit return type annotation with --isolatedDeclarations.
this.cleanups.push(fn)
}
}

/**
Expand Down Expand Up @@ -173,7 +182,7 @@
*/
export function onScopeDispose(fn: () => void, failSilently = false): void {
if (activeEffectScope) {
activeEffectScope.cleanups.push(fn)
activeEffectScope.onDispose(fn)
} else if (__DEV__ && !failSilently) {
warn(
`onScopeDispose() is called when there is no active effect scope` +
Expand Down
Loading