Skip to content

Instantly share code, notes, and snippets.

@taikulawo
Created May 7, 2020 10:11
Show Gist options
  • Save taikulawo/d39d589e8ab5d1c121f910ffe1fbed68 to your computer and use it in GitHub Desktop.
Save taikulawo/d39d589e8ab5d1c121f910ffe1fbed68 to your computer and use it in GitHub Desktop.
React Observable
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;
}
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