Skip to content

Reactive

hhh edited this page Jun 27, 2020 · 1 revision

Reactive

/**
 * Type of reactive getters/watchers/mappers
 */
type ReactiveGetter<T> = (currentValue: Readonly<T>) => void;
type ReactiveWatcher<T> = (action: T) => void;
type ReactiveMapper<T, U> = (originalValue: T) => U;

/**
 * Base class of reactive value
 */
declare abstract class Reactive<T, U> {

    constructor(initialValue: T);

    /**
     * Current value
     */
    current: T;

    protected _getters: ReactiveGetter<T>[];
    protected _watchers: ReactiveWatcher<U>[];

    /**
     * Add `this._update` to schedule
     */
    protected _setSchedule(): void;

    /**
     * Get the latest value asynchronously by providing a callback
     */
    get(getter: ReactiveGetter<T>): this;

    /**
     * Remove a previously registered getter
     */
    unget(getter: ReactiveGetter<T>): this;

    /**
     * Add a watcher that subscribes to the changes
     */
    watch(watcher: ReactiveWatcher<U>): this;

    /**
     * Remove a previously registered watcher
     */
    unwatch(watcher: ReactiveWatcher<U>): this;

    /**
     * The updater that updates the value
     * and deals with getters and watchers
     */
    abstract update(): void;

}
Clone this wiki locally