Skip to content

Instantly share code, notes, and snippets.

@bouzuya
Created September 4, 2016 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bouzuya/f49c8b8307c569ac27500ef4b7c44ef1 to your computer and use it in GitHub Desktop.
Save bouzuya/f49c8b8307c569ac27500ef4b7c44ef1 to your computer and use it in GitHub Desktop.
Raynos/observ other api
// `l-value` is inspired by observ@2.0.0
// https://github.com/Raynos/observ/tree/v0.2.0
export type Listener<T> = (newValue: T) => any;
export type Unlisten = () => void;
export interface LValue<T> {
get(): T;
listen(listener: Listener<T>): Unlisten;
set(newValue: T): void;
}
class LValueImpl<T> implements LValue<T> {
private readonly _listeners: Listener<T>[];
private _value: T;
constructor(initialValue: T) {
this._listeners = [];
this._value = initialValue;
}
get(): T {
return this._value;
}
listen(listener: Listener<T>): Unlisten {
this._listeners.push(listener);
return () => {
const index = this._listeners.indexOf(listener);
this._listeners.splice(index, 1);
};
}
set(newValue: T) {
this._value = newValue;
this._listeners.forEach((listener) => listener(newValue));
}
}
const lValue = <T>(initialValue: T): LValue<T> => new LValueImpl(initialValue);
export { lValue };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment