Last active
May 27, 2020 21:58
-
-
Save simontreny/d60f7eaa34ba230c2f1fab46831f22e2 to your computer and use it in GitHub Desktop.
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
type Listener<T> = (val: T) => void; | |
type Unsubscriber = () => void; | |
export class Observable<T> { | |
private _listeners: Listener<T>[] = []; | |
constructor(private _val: T) {} | |
get(): T { | |
return this._val; | |
} | |
set(val: T) { | |
if (this._val !== val) { | |
this._val = val; | |
this._listeners.forEach(l => l(val)); | |
} | |
} | |
subscribe(listener: Listener<T>): Unsubscriber { | |
this._listeners.push(listener); | |
return () => { | |
this._listeners = this._listeners.filter(l => l !== listener); | |
}; | |
} | |
} |
Yes, you're right, it's fixed now. Thanks! 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
shouldn't it be
private _listeners: Listener<T>[] = [];
?otherwise
this._listeners.push(listener);
will throw an this._listeners is undefined errorthanks for the article :)