Last active
May 20, 2024 18:24
-
-
Save helabenkhalfallah/b0fbcd2b842e9a06ad2fc0562049cf89 to your computer and use it in GitHub Desktop.
Reactive Store
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 to create a reactive store | |
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 setting a property value | |
set: function(target, property, value, receiver) { | |
// Update the value of the property | |
Reflect.set(target, property, value, receiver); | |
// 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 a function to unsubscribe | |
return function unsubscribe() { | |
const index = subscribers.indexOf(callback); | |
if (index !== -1) { | |
subscribers.splice(index, 1); | |
} | |
}; | |
} | |
// Return the getter, setter, and subscribe functions | |
return { | |
getState, | |
subscribe, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment