Created
August 17, 2021 18:43
-
-
Save Kangaroux/13ddb5573ee0878bd53efe7bfa41d291 to your computer and use it in GitHub Desktop.
Observable class for typescript
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
/** | |
* Simple class for managing callable observers. | |
*/ | |
export class Observable<Fn extends (...args) => any> { | |
private observers: Set<Fn> = new Set(); | |
add(o: Fn): void { | |
this.observers.add(o); | |
} | |
remove(o: Fn): void { | |
this.observers.delete(o); | |
} | |
notify(...args: Parameters<Fn>) { | |
for (const o of this.observers) { | |
o(...args); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Observers are stored using a
Set
so adding the same observer multiple times has no effect. As per the ECMA spec,notify()
will iterate through the observers in the order they were added.