Skip to content

Instantly share code, notes, and snippets.

@barelyhuman
Last active September 29, 2023 22:02
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 barelyhuman/7f24320691473ce913e9c7b2e10c5202 to your computer and use it in GitHub Desktop.
Save barelyhuman/7f24320691473ce913e9c7b2e10c5202 to your computer and use it in GitHub Desktop.
simple callback based store

store

Simple store to write code based on value changes

const s = store({ data: 1 });

s.onChange((v) => {
  console.log({ v });
});

s.value.data = 2;
export function store(e) {
let r = [],
t = {};
Object.defineProperty(t, "value", {
value: new Proxy(
{ __d: e },
{
get: (e, r) => e.__d[r],
set(e, t, n) {
(e.__d[t] = n), r.forEach((r) => r(e.__d));
return true
},
}
),
});
Object.defineProperty(t, "onChange", {
value: function e(t) {
return (
r.push(t),
() => {
r = r.filter((e) => !Object.is(e, t));
}
);
},
});
return t;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment