Created
May 7, 2020 10:11
-
-
Save taikulawo/d39d589e8ab5d1c121f910ffe1fbed68 to your computer and use it in GitHub Desktop.
React Observable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react"; | |
export function useObservable(obj, isasync = false) { | |
let asyncid = null; | |
const [originobj, setoriginobj] = useState(obj); | |
const handler = { | |
get: (target, prop) => { | |
// 递归创建并返回 | |
if (typeof target[prop] === "object" && target[prop] !== null) { | |
return new Proxy(target[prop], handler); | |
} | |
return Reflect.get(target, prop); | |
}, | |
set: (target, prop, value) => { | |
const result = Reflect.set(target, prop, value); | |
if (isasync) { | |
if (asyncid) { | |
clearTimeout(asyncid); | |
} | |
asyncid = setTimeout(() => { | |
setoriginobj(originobj); | |
}, 0); | |
} else { | |
setoriginobj(Object.assign({}, originobj)); | |
} | |
return result; | |
} | |
}; | |
const proxyobj = new Proxy(originobj, handler); | |
Reflect.defineProperty(proxyobj, originobj, { | |
value: '"$$origindata"' | |
}); | |
return proxyobj; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react"; | |
interface Reflect { | |
defineMetadata: any; | |
} | |
export function useObservable(obj, isasync = false) { | |
let asyncid = null; | |
const [originobj, setoriginobj] = useState(obj); | |
const handler = { | |
get: (target, prop) => { | |
// 递归创建并返回 | |
if (typeof target[prop] === "object" && target[prop] !== null) { | |
return new Proxy(target[prop], handler); | |
} | |
return Reflect.get(target, prop); | |
}, | |
set: (target, prop, value) => { | |
const result = Reflect.set(target, prop, value); | |
if (isasync) { | |
if (asyncid) { | |
clearTimeout(asyncid); | |
} | |
asyncid = setTimeout(() => { | |
setoriginobj(originobj); | |
}, 0); | |
} else { | |
setoriginobj(Object.assign({}, originobj)); | |
} | |
return result; | |
} | |
}; | |
const proxyobj = new Proxy(originobj, handler); | |
Reflect.defineProperty( proxyobj, originobj,{value:'"$$origindata"'}); | |
return proxyobj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment