Last active
March 4, 2025 20:58
-
-
Save kucukkanat/1118303029bdb10a2ae2894825f3ad01 to your computer and use it in GitHub Desktop.
Simple signals implementation
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
class Signal { | |
constructor(value) { | |
this.value = value; | |
this.subscribers = new Set(); | |
} | |
get() { | |
return this.value; | |
} | |
set(newValue) { | |
if (typeof this.value === 'object' && typeof newValue === 'object' && this.value !== null && newValue !== null) { | |
this.value = { ...this.value, ...newValue }; // Deep merge objects | |
} else { | |
this.value = newValue; | |
} | |
this.notify(); | |
} | |
subscribe(callback) { | |
this.subscribers.add(callback); | |
return () => this.subscribers.delete(callback); // Unsubscribe function | |
} | |
notify() { | |
this.subscribers.forEach(callback => callback(this.value)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment