1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2024-11-03 21:04:03 +08:00
pigallery2/common/event/Event.ts

31 lines
744 B
TypeScript
Raw Normal View History

2016-12-27 06:36:38 +08:00
function isFunction(functionToCheck: any) {
let getType = {};
2016-03-13 18:28:29 +08:00
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
export class Event<T> {
2016-12-27 06:36:38 +08:00
private handlers: {(data?: T): void;}[] = [];
2016-03-13 18:28:29 +08:00
2016-12-27 06:36:38 +08:00
public on(handler: {(data?: T): void}) {
if (!isFunction(handler)) {
2016-03-13 18:28:29 +08:00
throw new Error("Handler is not a function");
}
this.handlers.push(handler);
}
2016-12-27 06:36:38 +08:00
public off(handler: {(data?: T): void}) {
2016-03-13 18:28:29 +08:00
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));
}
}
}