UNPKG

@grandlinex/react-components

Version:
64 lines (63 loc) 1.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class LocalStorage { static on(name, listener) { if (!this.events.has(name)) { this.events.set(name, []); } this.events.get(name)?.push(listener); } static removeListener(name, listenerToRemove) { if (!this.events.has(name)) { throw new Error(`Can't remove a listener. Event "${name}" doesn't exits.`); } const filterListeners = (listener) => listener !== listenerToRemove; const ev = this.events.get(name)?.filter(filterListeners) || []; this.events.set(name, ev); } static emit(name, data) { if (this.events.has(name)) { const fireCallbacks = (callback) => { callback(data); }; this.events.get(name)?.forEach(fireCallbacks); } } static save(key, val) { window.localStorage.setItem(key, val); this.emit('update', key); } static load(key, defaultValue = '') { return window.localStorage.getItem(key) || defaultValue; } static jsonSave(key, val) { try { this.save(key, JSON.stringify(val)); return true; } catch (e) { return false; } } static jsonLoad(key) { try { return JSON.parse(this.load(key)); } catch (e) { return null; } } static flagSave(key, val) { this.save(key, val ? 'true' : 'false'); this.emit('flag-update', key); } static flagLoad(key) { return this.load(key, 'false') === 'true'; } static delete(key) { window.localStorage.removeItem(key); this.emit('update', key); } } LocalStorage.events = new Map(); exports.default = LocalStorage;