Skip to content

Instantly share code, notes, and snippets.

@kucukkanat
Last active March 4, 2025 20:58
Show Gist options
  • Save kucukkanat/1118303029bdb10a2ae2894825f3ad01 to your computer and use it in GitHub Desktop.
Save kucukkanat/1118303029bdb10a2ae2894825f3ad01 to your computer and use it in GitHub Desktop.
Simple signals implementation
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