Skip to content

Commit

Permalink
refactor(effectScope): restore parent scope after detached scope run …
Browse files Browse the repository at this point in the history
…/ off
  • Loading branch information
qq15725 committed Apr 5, 2022
1 parent 245230e commit a901c60
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
29 changes: 28 additions & 1 deletion packages/reactivity/__tests__/effectScope.spec.ts
Expand Up @@ -6,7 +6,8 @@ import {
onScopeDispose,
computed,
ref,
ComputedRef
ComputedRef,
getCurrentScope
} from '../src'

describe('reactivity/effect/scope', () => {
Expand Down Expand Up @@ -264,3 +265,29 @@ describe('reactivity/effect/scope', () => {
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
})
})

it('getCurrentScope() stays valid when running a detached nested EffectScope', () => {
const parentScope = new EffectScope()

parentScope.run(() => {
const currentScope = getCurrentScope()
expect(currentScope).toBeDefined()
const detachedScope = new EffectScope(true)
detachedScope.run(() => {})

expect(getCurrentScope()).toBe(currentScope)
})
})

it('getCurrentScope() stays valid when offed a detached nested EffectScope', () => {
const parentScope = new EffectScope()

parentScope.run(() => {
const currentScope = getCurrentScope()
expect(currentScope).toBeDefined()
const detachedScope = new EffectScope(true)
detachedScope.off()

expect(getCurrentScope()).toBe(currentScope)
})
})
8 changes: 4 additions & 4 deletions packages/reactivity/src/effectScope.ts
Expand Up @@ -17,8 +17,8 @@ export class EffectScope {
private index: number | undefined

constructor(detached = false) {
this.parent = activeEffectScope
if (!detached && activeEffectScope) {
this.parent = activeEffectScope
this.index =
(activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(
this
Expand Down Expand Up @@ -62,12 +62,12 @@ export class EffectScope {
}
}
// nested scope, dereference from parent to avoid memory leaks
if (this.parent && !fromParent) {
if (this.index !== undefined && this.parent && !fromParent) {
// optimized O(1) removal
const last = this.parent.scopes!.pop()
if (last && last !== this) {
this.parent.scopes![this.index!] = last
last.index = this.index!
this.parent.scopes![this.index] = last
last.index = this.index
}
}
this.active = false
Expand Down

0 comments on commit a901c60

Please sign in to comment.