/
effectScope.ts
130 lines (115 loc) · 2.63 KB
/
effectScope.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import {
ComponentInternalInstance,
getCurrentInstance,
getVueConstructor,
withCurrentInstanceTrackingDisabled,
} from '../runtimeContext'
import { defineComponentInstance } from '../utils'
import { warn } from './warn'
let activeEffectScope: EffectScope | undefined
const effectScopeStack: EffectScope[] = []
class EffectScopeImpl {
active = true
effects: EffectScope[] = []
cleanups: (() => void)[] = []
/**
* @internal
**/
vm: Vue
constructor(vm: Vue) {
this.vm = vm
}
run<T>(fn: () => T): T | undefined {
if (this.active) {
try {
this.on()
return fn()
} finally {
this.off()
}
} else if (__DEV__) {
warn(`cannot run an inactive effect scope.`)
}
return
}
on() {
if (this.active) {
effectScopeStack.push(this)
activeEffectScope = this
}
}
off() {
if (this.active) {
effectScopeStack.pop()
activeEffectScope = effectScopeStack[effectScopeStack.length - 1]
}
}
stop() {
if (this.active) {
this.vm.$destroy()
this.effects.forEach((e) => e.stop())
this.cleanups.forEach((cleanup) => cleanup())
this.active = false
}
}
}
export class EffectScope extends EffectScopeImpl {
constructor(detached = false) {
let vm: Vue = undefined!
withCurrentInstanceTrackingDisabled(() => {
vm = defineComponentInstance(getVueConstructor())
})
super(vm)
if (!detached) {
recordEffectScope(this)
}
}
}
export function recordEffectScope(
effect: EffectScope,
scope?: EffectScope | null
) {
scope = scope || activeEffectScope
if (scope && scope.active) {
scope.effects.push(effect)
return
}
// destory on parent component unmounted
const vm = getCurrentInstance()?.proxy
vm && vm.$on('hook:destroyed', () => effect.stop())
}
export function effectScope(detached?: boolean) {
return new EffectScope(detached)
}
export function getCurrentScope() {
return activeEffectScope
}
export function onScopeDispose(fn: () => void) {
if (activeEffectScope) {
activeEffectScope.cleanups.push(fn)
} else if (__DEV__) {
warn(
`onDispose() is called when there is no active effect scope` +
` to be associated with.`
)
}
}
/**
* @internal
**/
export function getCurrentScopeVM() {
return getCurrentScope()?.vm || getCurrentInstance()?.proxy
}
/**
* @internal
**/
export function bindCurrentScopeToVM(
vm: ComponentInternalInstance
): EffectScope {
if (!vm.scope) {
const scope = new EffectScopeImpl(vm.proxy) as EffectScope
vm.scope = scope
vm.proxy.$on('hook:destroyed', () => scope.stop())
}
return vm.scope
}