UNPKG

@nent/core

Version:

Functional elements to add routing, data-binding, dynamic HTML, declarative actions, audio, video, and so much more. Supercharge static HTML files into web apps without script or builds.

41 lines (40 loc) 1.54 kB
/*! * NENT 2022 */ import { DATA_EVENTS, } from '../../../services/data/interfaces'; /* It's a wrapper around the localStorage API that emits an event when the data changes */ export class StorageService { /** * `constructor` is a function that is called when a new instance of the class is created * @param {Window} win - Window - the window object * @param {IEventEmitter} eventBus - This is the event bus that we created in the previous step. * @param {string} name - The name of the provider. This is used to identify the provider when * emitting events. * @param {string} [prefix] - This is the prefix that will be used for all keys in the local storage. */ constructor(win, eventBus, name, prefix = '') { this.eventBus = eventBus; this.name = name; this.prefix = prefix; this.localStorage = win.localStorage; window === null || window === void 0 ? void 0 : window.addEventListener('storage', () => { this.eventBus.emit(DATA_EVENTS.DataChanged, { provider: this.name, }); }, { passive: true }); } async get(key) { var _a; return ((_a = this.localStorage) === null || _a === void 0 ? void 0 : _a.getItem(this.prefix + key)) || null; } async set(key, value) { var _a; const existing = await this.get(key); if (existing == value) return; (_a = this.localStorage) === null || _a === void 0 ? void 0 : _a.setItem(this.prefix + key, value); this.eventBus.emit(DATA_EVENTS.DataChanged, { provider: this.name, }); } }