UNPKG

stimulus-store

Version:

Lightweight state management for Stimulus.js

72 lines (71 loc) 2.64 kB
import type { CurrentValueCallback, SetOptions, StoreValue, Subscription, TypeKey } from 'types'; /** * @template T The type of the value that the store holds. * Store Class Explanation: * * The `Store` class is a versatile class for managing and subscribing to data updates in JavaScript applications. * It provides a structured way to store data and notify subscribers when the data changes. * * Key Features: * - Generic Class: Can work with different types of data (specified when creating an instance). * - Constructor: Sets the initial value of the store. * - `set` Method: Updates the value and notifies subscribers. * - `get` Method: Gets the current value. * - `subscribe` Method: Subscribes to updates and calls a callback function when data changes. * - `unsubscribe` Method: Removes a subscription. * - `notifySubscribers` Method: Notifies subscribers when data changes. */ export declare class Store { readonly name: symbol; private value; private initialValue; private subscribers; private type; /** * Creates a new store. * * @param {symbol} name - The name of the store. * @param {TypeKey} type - The type of the store's value. */ constructor(name: symbol, type: TypeKey); /** * Sets the value of the store and notifies subscribers. * * @param {T | CurrentValueCallback | Promise<T | CurrentValueCallback>} newValue - The new value. * @param {SetOptions} [options={ filter: () => true }] - The options for setting the value. */ set(newValue: StoreValue | CurrentValueCallback | Promise<StoreValue | CurrentValueCallback>, options?: SetOptions): Promise<void>; /** * Gets the current value of the store. * * @returns {StoreValue} The current value. */ get(): StoreValue; /** * Resets the store to its initial value. */ resetValue(): void; private setValue; private setInitialValue; /** * Subscribes to the store. * * @param {UpdateMethod} callback - The function to call when the store's value changes. * @returns {UnsubscribeFunction} A function that unsubscribes the callback. */ private subscribe; /** * Unsubscribes from the store. * * @param {UpdateMethod} callback - The function to unsubscribe. */ private unsubscribe; /** * Gets a subscription object with subscribe, when invoked subscribe returns an unsubscribe function. * * @returns {Subscription} A subscription object. */ getSubscription(): Subscription; private notifySubscribers; private resolvePromise; }