Skip to content

Instantly share code, notes, and snippets.

@clinuxrulz
Created February 13, 2019 05:30
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 clinuxrulz/8beed7b8eb9fcad06807c039bdd9ec9c to your computer and use it in GitHub Desktop.
Save clinuxrulz/8beed7b8eb9fcad06807c039bdd9ec9c to your computer and use it in GitHub Desktop.
wake-up / sleep listeners
class Test<A> {
private _value: A;
private _listeners: ((a:A)=>void)[] = [];
private _onWakeUp: () => {};
private _onSleep: () => {};
public constructor(value: A) {
this._value = value;
}
public listen(listener: (a:A)=>void): ()=>void {
if (this._listeners.length == 0) {
this._onWakeUp();
}
this._listeners.push(listener);
return () => {
for (var i = 0; i < this._listeners.length; ++i) {
if (this._listeners[i] === listener) {
this._listeners.splice(i, 1);
if (this._listeners.length == 0) {
this._onSleep();
}
return;
}
}
};
}
public map<B>(fn: (a:A)=>B): Test<B> {
var x = new Test(
fn(this._value)
);
x._onWakeUp = () => {
...
}
x._onSleep = ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment