Skip to content

Instantly share code, notes, and snippets.

@bouzuya

bouzuya/l-value.ts

Created Sep 4, 2016
Embed
What would you like to do?
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