Created
April 28, 2024 07:21
-
-
Save helabenkhalfallah/9a9a2d1e897dd2e033dd5c348dbc1a4e to your computer and use it in GitHub Desktop.
An example of a JavaScript proxy with callbacks
This file contains hidden or 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(initialState) { | |
// Store the initial state in a private variable | |
let state = initialState; | |
// Array to hold subscribers (callbacks) | |
const subscribers = []; | |
// Create a proxy for the state object | |
const stateProxy = new Proxy(state, { | |
// Trap for getting a property value | |
get: function(target, property, receiver) { | |
// No changes needed in this trap | |
return target[property]; | |
}, | |
// Trap for setting a property value | |
set: function(target, property, value, receiver) { | |
// Update the value of the property | |
target[property] = value; | |
// Trigger callbacks (subscribers) with the updated state | |
subscribers.forEach(callback => callback(stateProxy)); | |
// Indicate success | |
return true; | |
} | |
}); | |
// Function to get the current state | |
function getState() { | |
return stateProxy; | |
} | |
// Function to subscribe to state changes | |
function subscribe(callback) { | |
subscribers.push(callback); | |
} | |
// Return the getter, setter, and subscribe functions | |
return { | |
getState, | |
subscribe | |
}; | |
} | |
// Usage example | |
const store = createStore({ count: 0 }); | |
// Subscribe to state changes | |
store.subscribe(state => { | |
console.log("State changed:", state); | |
}); | |
// Accessing properties through the getter | |
console.log(store.getState().count); // Output: 0 | |
// Updating the state through the setter | |
store.getState().count = 10; // Output: "State changed: { count: 10 }" | |
// Accessing properties through the getter | |
console.log(store.getState().count); // Output: 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment