Skip to content

Commit

Permalink
feat(effectScope): allow multiple calls by tracking call count
Browse files Browse the repository at this point in the history
  • Loading branch information
edison1105 committed Jan 3, 2025
1 parent ef6986f commit 043eb35
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
13 changes: 13 additions & 0 deletions packages/reactivity/__tests__/effectScope.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,19 @@ describe('reactivity/effect/scope', () => {
})
})

it('calling on() and off() multiple times inside an active scope should not break currentScope', () => {
const parentScope = effectScope()
parentScope.run(() => {
const childScope = effectScope(true)
childScope.on()
childScope.on()
childScope.off()
childScope.off()
childScope.off()
expect(getCurrentScope()).toBe(parentScope)
})
})

it('should pause/resume EffectScope', async () => {
const counter = reactive({ num: 0 })
const fnSpy = vi.fn(() => counter.num)
Expand Down
16 changes: 13 additions & 3 deletions packages/reactivity/src/effectScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export class EffectScope {
* @internal
*/
private _active = true
/**
* @internal track `on` calls, allow `on` call multiple times
*/
private _onCallCount = 0
/**
* @internal
*/
Expand Down Expand Up @@ -105,16 +109,22 @@ export class EffectScope {
* @internal
*/
on(): void {
this.prevScope = activeEffectScope
activeEffectScope = this
this._onCallCount++
if (this._onCallCount === 1) {
this.prevScope = activeEffectScope
activeEffectScope = this
}
}

/**
* This should only be called on non-detached scopes
* @internal
*/
off(): void {
activeEffectScope = this.prevScope
this._onCallCount = Math.max(0, this._onCallCount - 1)
if (this._onCallCount === 0) {
activeEffectScope = this.prevScope
}
}

stop(fromParent?: boolean): void {
Expand Down

0 comments on commit 043eb35

Please sign in to comment.