Created
September 4, 2016 03:40
-
-
Save bouzuya/f49c8b8307c569ac27500ef4b7c44ef1 to your computer and use it in GitHub Desktop.
Raynos/observ other api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// `l-value` is inspired by [email protected] | |
// 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