wip: writable computed

This commit is contained in:
Evan You 2019-06-06 12:35:49 +08:00
parent e9a3fa60d6
commit 39e1fffb9c

View File

@ -7,13 +7,13 @@ export interface ComputedValue<T> {
readonly effect: ReactiveEffect readonly effect: ReactiveEffect
} }
export function computed<T, C = null>( export function computed<T>(
getter: (this: C, ctx: C) => T, getter: () => T,
context?: C setter?: (v: T) => void
): ComputedValue<T> { ): ComputedValue<T> {
let dirty: boolean = true let dirty: boolean = true
let value: any = undefined let value: any = undefined
const runner = effect(() => getter.call(context, context), { const runner = effect(getter, {
lazy: true, lazy: true,
// mark effect as computed so that it gets priority during trigger // mark effect as computed so that it gets priority during trigger
computed: true, computed: true,
@ -34,6 +34,13 @@ export function computed<T, C = null>(
// This should also apply for chained computed properties. // This should also apply for chained computed properties.
trackChildRun(runner) trackChildRun(runner)
return value return value
},
set value(newValue) {
if (setter) {
setter(newValue)
} else {
// TODO warn attempting to mutate readonly computed value
}
} }
} }
knownValues.add(computedValue) knownValues.add(computedValue)