Created
December 6, 2024 04:34
-
-
Save im4aLL/0ccef29aa29048911e557f6e703dc7c8 to your computer and use it in GitHub Desktop.
minimal implementation of signal
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
const signal = (value) => { | |
const fn = () => value; | |
let subscribers = []; | |
const notifySubscribers = () => { | |
subscribers.forEach((subscriber) => subscriber(value)); | |
}; | |
fn.set = (newValue) => { | |
value = newValue; | |
notifySubscribers(); | |
}; | |
fn.update = (callback) => { | |
value = callback(value); | |
return value; | |
}; | |
fn.subscribe = (callback) => { | |
const count = subscribers.push(callback); | |
return { | |
unsubscribe: () => { | |
subscribers = subscribers.slice(0, count - 1); | |
}, | |
}; | |
}; | |
return fn; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment