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

33 lines
697 B
TypeScript
Raw Normal View History

2019-05-29 17:36:53 +08:00
import { track, trigger } from './effect'
import { OperationTypes } from './operations'
2019-05-29 18:44:50 +08:00
import { isObject } from '@vue/shared'
import { observable } from './index'
2019-05-29 17:36:53 +08:00
2019-05-29 18:44:50 +08:00
export const knownValues = new WeakSet()
2019-05-29 17:36:53 +08:00
export interface Value<T> {
value: T
}
2019-05-29 18:44:50 +08:00
const convert = (val: any): any => (isObject(val) ? observable(val) : val)
2019-05-29 17:36:53 +08:00
export function value<T>(raw: T): Value<T> {
2019-05-29 18:44:50 +08:00
raw = convert(raw)
2019-05-29 17:36:53 +08:00
const v = {
get value() {
track(v, OperationTypes.GET, '')
return raw
},
set value(newVal) {
2019-05-29 18:44:50 +08:00
raw = convert(newVal)
2019-05-29 17:36:53 +08:00
trigger(v, OperationTypes.SET, '')
}
}
knownValues.add(v)
return v
}
export function isValue(v: any): boolean {
return knownValues.has(v)
}