Options
All
  • Public
  • Public/Protected
  • All
Menu

A Observable is a value that can be observed for changes.

This observation can happen using 2 mechanisms: Watchers and Observers.

Watchers

Watchers are simple functions that get called when the observable value changes.

They receive the new and old value of the observable as arguments.

const observable = new Observable(20);

observable.watch((value, oldValue) => {
 console.log(value, oldValue);
});

observable.update(15); // output: 15 20

Observers

Observers are ComputedObservables that use other Observables to determine their values.

When the observable changes then observers are updated.

const observable = new Observable(20);
const computedObservable = new ComputedObservable(() => observable.value * 2);

console.log(computedObservable.value); // output: 40

observable.observe(computedObservable);

// Since the computed observable is now 'observed' it will get updated when the observable changes.
observable.update(15);

console.log(computedObservable.value); // output: 30

Type parameters

  • T

    Any valid javascript value.

Hierarchy

Index

Constructors

constructor

  • new Observable(value: T | undefined): Observable

Properties

Protected _observers

_observers: ComputedObservable<unknown>[] = []

List of ComputedObservables that need to be updated when value changes.

Protected _watchers

_watchers: WatcherFunction<T>[] = []

List of WatcherFunctions that get run when the observable value changes.

value

value: T | undefined

Current value of the observable.

Methods

observe

unobserve

unwatch

update

  • update(value: T | undefined): void
  • Method used to update the value property.

    Parameters

    • value: T | undefined

      New value of the observable.

    Returns void

watch

Generated using TypeDoc