Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Last active April 28, 2024 13:03
Show Gist options
  • Select an option

  • Save helabenkhalfallah/585b08abf140b7dc07c3b77ce5df23d8 to your computer and use it in GitHub Desktop.

Select an option

Save helabenkhalfallah/585b08abf140b7dc07c3b77ce5df23d8 to your computer and use it in GitHub Desktop.
Simplified version of createSignal
function createSignal(initialValue) {
let value = initialValue; // Internal state to hold the current value of the signal
const subscribers = new Set(); // Set to keep track of subscribers (components or functions that depend on the signal)
// Getter function to retrieve the current value of the signal
function get() {
return value;
}
// Setter function to update the value of the signal and notify subscribers
function set(newValue) {
value = newValue; // Update the internal state with the new value
// Notify all subscribers by calling their update functions
subscribers.forEach(subscriber => subscriber());
}
// Function to subscribe to the signal and receive updates
function subscribe(updateFunction) {
subscribers.add(updateFunction); // Add the update function to the subscribers set
// Return a function to unsubscribe and remove the update function from subscribers set
return () => subscribers.delete(updateFunction);
}
// Return the getter, setter, and subscribe functions as an array
return [get, set, subscribe];
}
// Example usage:
const [count, setCount, subscribe ] = createSignal(0);
console.log('count: ', count()); // 0
setCount(12); // update the state
console.log('count: ', count()); // 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment