Skip to content

Instantly share code, notes, and snippets.

@wonglok
Last active September 25, 2021 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wonglok/0b2ad89ea77a9bed603e6277a8a40e48 to your computer and use it in GitHub Desktop.
Save wonglok/0b2ad89ea77a9bed603e6277a8a40e48 to your computer and use it in GitHub Desktop.
Shallow Store
import { useEffect, useState } from "react";
export const getID = function () {
return (
"_" +
Math.random().toString(36).substr(2, 9) +
Math.random().toString(36).substr(2, 9)
);
};
export const ShallowStoreMethods = {
onEvent: () => {},
makeKeyReactive: () => {},
reloadKey: () => {},
};
/**
* @returns {ShallowStoreMethods}
*/
export const makeShallowStore = (myObject = {}) => {
let ___NameSpaceID = getID();
let Utils = {
exportJSON: () => {
return JSON.parse(JSON.stringify(myObject));
},
/* */
getNameSpcaeID: () => {
return ___NameSpaceID;
},
/* */
onEvent: (key, func) => {
let evName = `${___NameSpaceID}`;
let hh = () => {
func(myObject[key]);
};
window.addEventListener(`${evName}-${key}`, hh);
return () => {
window.removeEventListener(`${evName}-${key}`, hh);
};
},
makeKeyReactive: (key) => {
let [vv, setSt] = useState(0);
useEffect(() => {
let evName = `${___NameSpaceID}`;
let hh = () => {
setSt((s) => {
return s + 1;
});
};
window.addEventListener(`${evName}-${key}`, hh);
return () => {
window.removeEventListener(`${evName}-${key}`, hh);
};
}, [vv]);
},
reloadKey: (key) => {
window.dispatchEvent(
new CustomEvent(`${___NameSpaceID}-${key}`, { detail: {} })
);
},
};
let proxy = new Proxy(myObject, {
get: (o, k) => {
//
if (Utils[k]) {
return Utils[k];
}
return o[k];
},
set: (o, key, val) => {
let currentVal = o[key];
if (currentVal !== val) {
o[key] = val;
if (typeof window !== "undefined") {
window.dispatchEvent(
new CustomEvent(`${___NameSpaceID}-${key}`, { detail: {} })
);
}
}
return true;
},
});
let Type = {
...myObject,
...ShallowStoreMethods,
};
/** @type {Type} */
return proxy;
};
/* Usage demo: */
let UI = makeShallowStore({
name: "lok",
});
function Compo() {
UI.makeKeyReactive("name");
return <div>{UI.name}</div>;
}
function Compo2() {
return (
<div>
<button
onClick={() => {
UI.name = "ha " + Math.random();
}}
></button>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment