Last active
December 1, 2022 17:50
-
-
Save dturton/95af893392228040f727ce7203bb31a4 to your computer and use it in GitHub Desktop.
JavaScript Proxy example use case
This file contains 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
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