refactor: editor events sub/unsub refactor (#7483)

This commit is contained in:
David Luzar 2023-12-30 11:12:38 +01:00 committed by GitHub
parent 5f40a4cad4
commit c72e853c85
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 186 additions and 129 deletions

View file

@ -1,3 +1,5 @@
import { UnsubscribeCallback } from "./types";
type Subscriber<T extends any[]> = (...payload: T) => void;
export class Emitter<T extends any[] = []> {
@ -15,7 +17,7 @@ export class Emitter<T extends any[] = []> {
*
* @returns unsubscribe function
*/
on(...handlers: Subscriber<T>[] | Subscriber<T>[][]) {
on(...handlers: Subscriber<T>[] | Subscriber<T>[][]): UnsubscribeCallback {
const _handlers = handlers
.flat()
.filter((item) => typeof item === "function");
@ -25,6 +27,17 @@ export class Emitter<T extends any[] = []> {
return () => this.off(_handlers);
}
once(...handlers: Subscriber<T>[] | Subscriber<T>[][]): UnsubscribeCallback {
const _handlers = handlers
.flat()
.filter((item) => typeof item === "function");
_handlers.push(() => detach());
const detach = this.on(..._handlers);
return detach;
}
off(...handlers: Subscriber<T>[] | Subscriber<T>[][]) {
const _handlers = handlers.flat();
this.subscribers = this.subscribers.filter(