vue3-yuanma/packages/observer/src/computed.ts

52 lines
1.4 KiB
TypeScript
Raw Normal View History

2018-11-14 00:03:35 +08:00
import { effect } from './index'
import { ReactiveEffect, activeReactiveEffectStack } from './effect'
2018-09-19 23:35:38 +08:00
export interface ComputedGetter<T = any> {
(): T
2018-11-14 00:03:35 +08:00
effect: ReactiveEffect
2018-09-19 23:35:38 +08:00
}
export function computed<T, C = null>(
getter: (this: C, ctx: C) => T,
context?: C
): ComputedGetter<T> {
2018-09-19 23:35:38 +08:00
let dirty: boolean = true
let value: any = undefined
2018-11-14 00:03:35 +08:00
const runner = effect(() => getter.call(context, context), {
2018-09-19 23:35:38 +08:00
lazy: true,
scheduler: () => {
dirty = true
}
})
const computedGetter = (() => {
if (dirty) {
value = runner()
dirty = false
}
2018-11-14 00:03:35 +08:00
// When computed effects are accessed in a parent effect, the parent
2018-09-19 23:35:38 +08:00
// should track all the dependencies the computed property has tracked.
// This should also apply for chained computed properties.
trackChildRun(runner)
return value
}) as ComputedGetter
2018-11-14 00:03:35 +08:00
// expose effect so computed can be stopped
computedGetter.effect = runner
// mark effect as computed so that it gets priority during trigger
2018-09-21 06:36:34 +08:00
runner.computed = true
2018-09-19 23:35:38 +08:00
return computedGetter
}
2018-11-14 00:03:35 +08:00
function trackChildRun(childRunner: ReactiveEffect) {
const parentRunner =
activeReactiveEffectStack[activeReactiveEffectStack.length - 1]
2018-09-19 23:35:38 +08:00
if (parentRunner) {
for (let i = 0; i < childRunner.deps.length; i++) {
const dep = childRunner.deps[i]
if (!dep.has(parentRunner)) {
dep.add(parentRunner)
parentRunner.deps.push(dep)
}
}
}
}