Last active
February 24, 2026 10:39
-
-
Save belyas/a1a36d90b0e80f0ba9229f300e83034a to your computer and use it in GitHub Desktop.
Mental-model implementation of Signals in Javascript
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
| // A global variable to track the currently running effect | |
| let currentEffect = null; | |
| function createSignal(initialValue) { | |
| let value = initialValue; | |
| const subscribers = new Set(); | |
| return { | |
| get value() { | |
| // 1. Dependency Tracking: If an effect is running, subscribe it! | |
| if (currentEffect) { | |
| subscribers.add(currentEffect); | |
| } | |
| return value; | |
| }, | |
| set value(newValue) { | |
| // 2. Notification: Update value and trigger all subscribers | |
| if (value !== newValue) { | |
| value = newValue; | |
| subscribers.forEach(effect => effect()); | |
| } | |
| } | |
| }; | |
| } | |
| function createEffect(effectFn) { | |
| // Set the global context so the Signal knows WHO is reading it | |
| currentEffect = effectFn; | |
| effectFn(); // Run it once to trigger the getters | |
| currentEffect = null; // Cleanup | |
| } | |
| // Now, let's use our custom Signal: | |
| const count = createSignal(0); | |
| const multiplier = createSignal(2); | |
| // This effect automatically tracks `count` and `multiplier` | |
| createEffect(() => { | |
| element.innerText = `Total: ${count.value * multiplier.value}`; | |
| }); | |
| // 💻 Element text: "Total: 0" | |
| count.value = 5; | |
| // 💻 Element text: "Total: 10" (Automatically re-ran!) | |
| multiplier.value = 3; | |
| // 💻 Element text: "Total: 15" (Automatically re-ran!) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment