1
0
mirror of https://github.com/bpatrik/pigallery2.git synced 2024-12-14 11:23:17 +02:00
pigallery2/common/event/Event.ts

31 lines
688 B
TypeScript

function isFunction(functionToCheck: any) {
let getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
export class Event<T> {
private handlers: { (data?: T): void; }[] = [];
public on(handler: { (data?: T): void }) {
if (!isFunction(handler)) {
throw new Error("Handler is not a function");
}
this.handlers.push(handler);
}
public off(handler: { (data?: T): void }) {
this.handlers = this.handlers.filter(h => h !== handler);
}
public allOff() {
this.handlers = [];
}
public trigger(data?: T) {
if (this.handlers) {
this.handlers.slice(0).forEach(h => h(data));
}
}
}