Skip to content

Instantly share code, notes, and snippets.

@dturton
Last active December 1, 2022 17:50
Show Gist options
  • Save dturton/95af893392228040f727ce7203bb31a4 to your computer and use it in GitHub Desktop.
Save dturton/95af893392228040f727ce7203bb31a4 to your computer and use it in GitHub Desktop.
JavaScript Proxy example use case
function createStore(target, listener) {
const handler = {
set(target, prop, value, receiver) {
target[prop] = value;
listener(receiver);
return true;
},
get(target, prop) {
return target[prop];
},
};
return new Proxy(target, handler);
}
const initialState = {
authenticated: false,
userName: "Sam",
favorites: []
};
function appListener(state) {
if (state.authenticated) {
// update UI
}
if (state.favorites.length) {
// update UI
}
}
const store = createStore(initialState, appListener);
// Some other part of the application makes
// these updates
store.authenticated = true;
store.favorites = ["Pizza", "Tacos"];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment