@signaldb/core
Version:
SignalDB is a client-side database that provides a simple MongoDB-like interface to the data with first-class typescript support to achieve an optimistic UI. Data persistence can be achieved by using storage providers that store the data through a JSON in
62 lines (61 loc) • 2.79 kB
TypeScript
type AddedCallback<T> = (item: T) => void;
type AddedBeforeCallback<T> = (item: T, before: T) => void;
type ChangedCallback<T> = (item: T) => void;
type ChangedFieldCallback<T> = <Field extends keyof T>(item: T, field: Field, oldValue: T[Field], newValue: T[Field]) => void;
type MovedBeforeCallback<T> = (item: T, before: T) => void;
type RemovedCallback<T> = (item: T) => void;
export interface ObserveCallbacks<T> {
added?: AddedCallback<T>;
addedBefore?: AddedBeforeCallback<T>;
changed?: ChangedCallback<T>;
changedField?: ChangedFieldCallback<T>;
movedBefore?: MovedBeforeCallback<T>;
removed?: RemovedCallback<T>;
}
/**
* Represents an observer that tracks changes in a collection of items and triggers
* callbacks for various events such as addition, removal, and modification of items.
* @template T - The type of the items being observed, which must include an `id` field.
*/
export default class Observer<T extends {
id: any;
}> {
private previousItems;
private callbacks;
private unbindEvents;
/**
* Creates a new instance of the `Observer` class.
* Sets up event bindings and initializes the callbacks for tracking changes in a collection.
* @param bindEvents - A function to bind external events to the observer. Must return a cleanup function to unbind those events.
*/
constructor(bindEvents: () => () => void);
private call;
private hasCallbacks;
/**
* Determines if the observer has no active callbacks registered for any events.
* @returns A boolean indicating whether the observer is empty (i.e., no callbacks are registered).
*/
isEmpty(): boolean;
/**
* Compares the previous state of items with the new state and triggers the appropriate callbacks
* for events such as added, removed, changed, or moved items.
* @param newItems - The new list of items to compare against the previous state.
*/
runChecks(newItems: T[]): void;
/**
* Stops the observer by unbinding all events and cleaning up resources.
*/
stop(): void;
/**
* Registers callbacks for specific events to observe changes in the collection.
* @param callbacks - An object containing the callbacks for various events (e.g., 'added', 'removed').
* @param skipInitial - A boolean indicating whether to skip invoking the callbacks for the initial state of the collection.
*/
addCallbacks(callbacks: ObserveCallbacks<T>, skipInitial?: boolean): void;
/**
* Removes the specified callbacks for specific events, unregistering them from the observer.
* @param callbacks - An object containing the callbacks to be removed for various events.
*/
removeCallbacks(callbacks: ObserveCallbacks<T>): void;
}
export {};