Created
October 21, 2024 09:38
-
-
Save tluyben/d36e4140b19ae3bfbde77a476da10574 to your computer and use it in GitHub Desktop.
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
class ReactiveLocalStorage { | |
constructor() { | |
this.listeners = {}; | |
} | |
setItem(key, value) { | |
localStorage.setItem(key, value); | |
this.notify(key, value); | |
} | |
getItem(key) { | |
return localStorage.getItem(key); | |
} | |
removeItem(key) { | |
localStorage.removeItem(key); | |
this.notify(key, null); | |
} | |
clear() { | |
localStorage.clear(); | |
Object.keys(this.listeners).forEach(key => this.notify(key, null)); | |
} | |
subscribe(key, callback) { | |
if (!this.listeners[key]) this.listeners[key] = []; | |
this.listeners[key].push(callback); | |
} | |
unsubscribe(key, callback) { | |
if (!this.listeners[key]) return; | |
this.listeners[key] = this.listeners[key].filter(cb => cb !== callback); | |
} | |
notify(key, value) { | |
if (!this.listeners[key]) return; | |
this.listeners[key].forEach(callback => callback(value)); | |
} | |
} | |
// Usage example: | |
const reactiveStorage = new ReactiveLocalStorage(); | |
reactiveStorage.subscribe('myKey', newValue => { | |
console.log('myKey changed to', newValue); | |
}); | |
reactiveStorage.setItem('myKey', 'hello'); // Logs: myKey changed to hello | |
reactiveStorage.setItem('myKey', 'world'); // Logs: myKey changed to world | |
reactiveStorage.removeItem('myKey'); // Logs: myKey changed to null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment