Slash-The-Hordes/assets/Scripts/Services/EventSystem/Signal.ts

29 lines
911 B
TypeScript
Raw Normal View History

2022-11-14 15:35:47 +00:00
// Need to capture *this*
/* eslint-disable @typescript-eslint/no-explicit-any */
import { ISignal } from "./ISignal";
export class Signal<T> implements ISignal<T> {
private handlers: ((data: T) => void)[] = [];
2022-11-08 18:45:57 +00:00
private thisArgs: any[] = [];
2022-11-08 18:45:57 +00:00
public on(handler: (data: T) => void, thisArg: any): void {
this.handlers.push(handler);
2022-11-08 18:45:57 +00:00
this.thisArgs.push(thisArg);
}
public off(handler: (data: T) => void): void {
2022-11-14 15:35:47 +00:00
const index: number = this.handlers.indexOf(handler);
this.handlers.splice(index, 1);
this.thisArgs.splice(index, 1);
}
public trigger(data: T): void {
2022-11-16 11:26:20 +00:00
// protect from trigger >> off
const handlers: ((data: T) => void)[] = [...this.handlers];
const thisArgs: any[] = [...this.thisArgs];
for (let i = 0; i < handlers.length; i++) {
handlers[i].call(thisArgs[i], data);
2022-11-08 18:45:57 +00:00
}
}
}