import { isReactive, reactive } from "../reactive"
describe("reactive", () => {
it("happy path", () => {
const original = {foo: 1}
const observed = reactive(original)
expect(observed).not.toBe(original)
expect(observed.foo).toBe(1)
+ expect(isReactive(observed)).toBe(true)
+ expect(isReactive(original)).toBe(false)
})
})
export const enum ReactiveFlags {
IS_REACTIVE = '_v_isReactive'
}
export function isReactive(value) {
// 这里之所以要取反是因为不是 reactive 不会走 baseHandlers 里的 createGetter
return !!value[ReactiveFlags.IS_REACTIVE]
}
function createGetter(isReadonly = false) {
return function get(target, key) {
console.log(key)
if (key === ReactiveFlags.IS_REACTIVE) {
return !isReadonly
}
const res = Reflect.get(target, key)
if (!isReadonly) {
track(target, key)
}
return res
}
}
isReadonly
export const enum ReactiveFlags {
IS_READONLY = '_v_isReadonly'
}
export function isReadonly(value) {
return !!value[ReactiveFlags.IS_READONLY]
}
describe("readonly", () => {
it("should make nested values readonly", () => {
const original = {foo: 1, bar: {baz: 2}}
const wrapped = readonly(original)
expect(isReadonly(wrapped)).toBe(true)
})
function createGetter(isReadonly = false) {
return function get(target, key) {
console.log(key)
if (key === ReactiveFlags.IS_REACTIVE) {
return !isReadonly
} else if (key === ReactiveFlags.IS_READONLY) {
return isReadonly
}
const res = Reflect.get(target, key)
if (!isReadonly) {
track(target, key)
}
return res
}
}
网友评论