Skip to content
Alexandre Moreau-Lemay edited this page Aug 22, 2022 · 7 revisions

A simple store that implements the Observer Pattern.

Implementation

class Store<T> implements Subject<T> {
    constructor(state: T);

    public get state(): T;
 
    public attach(observer: Observer<T>): void;
    public detach(observer: Observer<T>): void;
    public notify(): void;
    public set(options: T | ((prevState: T) => T)): void;

    static newPointer(): string;
}

Type parameter

  • T

Any serializable type

Implements

  • Subject<T>

Properties

state: T readonly

A deep clone of the internal state, to prevent referenced objects being directly mutated.

Static Methods

newPointer

newPointer(): string

Convenience method to create a unique pointer.

Methods

Attach

attach(observer: Observer<T>): void

Attaches/subscribes a new Observer to the store.

Parameters

  • observer: Observer<T>

    Observer to be attached to the store


Detach

detach(observer: Observer<T>): void

Detaches/unsubscribes an Observer from the store.

Parameters

  • observer: Observer<T>

    The Observer to detach


Notify

notify(): void

Notifies all the observers of a change. Will triffer automatically when the state is changed through Store.set(), but it can be forced by calling this method directly.


Set

set(options: T | ((prevState: T) => T)): void

Method to mutate the internal state. If a value is directly provided, assign the internal state to that value. A function can also be provided to access a dereferenced copy of the previous state.

Parameters

  • options: T | ((prevState: T) => T)

    A value to set the new state, or a function that receives the previous state to manipulate it.

Clone this wiki locally