Skip to content

feat(effectScope): add onDispose method #10826

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

Open
wants to merge 11 commits into
base: minor
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/reactivity/__tests__/effectScope.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,17 @@ describe('reactivity/effect/scope', () => {
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)
})

test('removing a watcher while stopping its effectScope', async () => {
const count = ref(0)
const scope = effectScope()
Expand Down
11 changes: 10 additions & 1 deletion packages/reactivity/src/effectScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ export class EffectScope implements ReactiveNode {
this.flags = 0
cleanup(this)
}

/**
* 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): void {
this.cleanups[this.cleanupsLength++] = fn
}
}

/**
Expand Down Expand Up @@ -135,7 +144,7 @@ export function setCurrentScope(scope?: EffectScope): EffectScope | undefined {
*/
export function onScopeDispose(fn: () => void, failSilently = false): void {
if (activeEffectScope !== undefined) {
activeEffectScope.cleanups[activeEffectScope.cleanupsLength++] = fn
activeEffectScope.onDispose(fn)
} else if (__DEV__ && !failSilently) {
warn(
`onScopeDispose() is called when there is no active effect scope` +
Expand Down