Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Created April 28, 2024 07:20
Show Gist options
  • Save helabenkhalfallah/3ba276fecb9a5f084789ea6a4a7f6833 to your computer and use it in GitHub Desktop.
Save helabenkhalfallah/3ba276fecb9a5f084789ea6a4a7f6833 to your computer and use it in GitHub Desktop.
An example of a JavaScript proxy
// Function to create a reactive store
function createStore(initialState) {
// Store the initial state in a private variable
let state = initialState;
// Create a proxy for the state object
const stateProxy = new Proxy(state, {
// Trap for getting a property value
get: function(target, property, receiver) {
console.log(`Getting property '${property}'`);
// Return the value of the property
return target[property];
},
// Trap for setting a property value
set: function(target, property, value, receiver) {
console.log(`Setting property '${property}' to '${value}'`);
// Update the value of the property
target[property] = value;
// Indicate success
return true;
}
});
// Function to get the current state
function getState() {
return stateProxy;
}
// Function to update the state
function setState(newState) {
// Loop through the properties of the new state
for (const key in newState) {
// Use the proxy's setter to update each property
stateProxy[key] = newState[key];
}
}
// Return the getter and setter functions
return {
getState, // Getter function to retrieve the current state
setState // Setter function to update the state
};
}
// Usage example
const store = createStore({
count: 0
});
// Accessing properties through the getter
console.log(store.getState().count); // Output: Getting property 'count', 0
// Updating the state through the setter
store.setState({
count: 10
}); // Output: Setting property 'count' to '10'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment