Skip to content

Instantly share code, notes, and snippets.

@simontreny
Last active May 27, 2020 21:58
Show Gist options
  • Save simontreny/d60f7eaa34ba230c2f1fab46831f22e2 to your computer and use it in GitHub Desktop.
Save simontreny/d60f7eaa34ba230c2f1fab46831f22e2 to your computer and use it in GitHub Desktop.
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);
};
}
}
@johnrees
Copy link

shouldn't it be private _listeners: Listener<T>[] = [];?

otherwise this._listeners.push(listener); will throw an this._listeners is undefined error

thanks for the article :)

@simontreny
Copy link
Author

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