Observers
A light implementation of JavaScript observables
Installation
npm install observers --save
Sample
; var obj = obs;; obj;; var array = obs; ; array; array; // 'a' array; // 3 array; // '['a', 'b'] array; // ['a', 'b', 'c', 'e'] array; // ['a', 'b', 'c'] // ...
API
observe
: Observable<T>; // Examplevar anObservable = obs.observe(5);var another = obs.observe(5);another(7);
observeArray
: ObservableArray<T>; // Examplevar obsArray = obs.observeArray([1,2,3,4,5,6]);
computed
Computed observables that depend on other observables (object
, array
or computed
) will re-evaluate
when their dependent observables are modifed.
See the below example:
: Computed<T>; // Example (using above example values)var comp = obs.computed(() => anObservable() + another()); // 12comp.subscribe(value => console.log(`My computed changed to ${value}`);another(9); // Will cause the computed to re-evaluate and notify subscribers
Shared functions
All observables (Obervable
, ObservableArray
, Computed
) have the following functions:
getter
Returns the current value of an observable with no side effects
: any; // Examplevar someNumber = obs.observe(12);someNumber(); // Returns 12 with no side effects
subscribe
Takes a function that will be called with the new value of an observable
: void; // ExamplesomeComputed.subscribe(newValue => $.post('/api/something', { data: newValue });
removeSubscribers
Remove all listener functions on a specific observable.
Warning: May have undesirable side effects.
; // ExamplesomeObservable.removeSubscribers();
Supported array functions
every
: boolean;
find
: T;
findIndex
: number;
filter
: Array<T>;
join
: string;
map
: Array<any>;
pop
: T;
push
: number;
reverse
: Array<T>;
reduce
: U;
remove
Returns an array of the removed items
: Array<T>;
removeAll
Returns an array of the removed items
: Array<T>;
removeSubscribers
Clears the list of subscribers
: void;
shift
: number;
slice
: Array<T>;
sort
: Array<T>;
splice
: Array<T>;
subscribe
Subscribes to changes to the observable
: void;
some
: boolean;
unshift
: number;
update
Returns the newValue
if successful.
Returns undefined
if unsuccessful.
: T;