2016-12-27 06:36:38 +08:00
|
|
|
function isFunction(functionToCheck: any) {
|
2018-05-13 00:19:51 +08:00
|
|
|
const getType = {};
|
2017-06-11 04:32:56 +08:00
|
|
|
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
|
2016-03-13 18:28:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
export class Event<T> {
|
2018-05-13 00:19:51 +08:00
|
|
|
private handlers: ((data?: T) => void)[] = [];
|
2016-03-13 18:28:29 +08:00
|
|
|
|
2018-05-13 00:19:51 +08:00
|
|
|
public on(handler: (data?: T) => void) {
|
2017-06-11 04:32:56 +08:00
|
|
|
if (!isFunction(handler)) {
|
2018-05-13 00:19:51 +08:00
|
|
|
throw new Error('Handler is not a function');
|
2016-03-13 18:28:29 +08:00
|
|
|
}
|
2017-06-11 04:32:56 +08:00
|
|
|
this.handlers.push(handler);
|
|
|
|
}
|
2016-03-13 18:28:29 +08:00
|
|
|
|
2018-05-13 00:19:51 +08:00
|
|
|
public off(handler: (data?: T) => void) {
|
2017-06-11 04:32:56 +08:00
|
|
|
this.handlers = this.handlers.filter(h => h !== handler);
|
|
|
|
}
|
2016-03-13 18:28:29 +08:00
|
|
|
|
2017-06-11 04:32:56 +08:00
|
|
|
public allOff() {
|
|
|
|
this.handlers = [];
|
|
|
|
}
|
2016-03-13 18:28:29 +08:00
|
|
|
|
2017-06-11 04:32:56 +08:00
|
|
|
public trigger(data?: T) {
|
|
|
|
if (this.handlers) {
|
|
|
|
this.handlers.slice(0).forEach(h => h(data));
|
2016-03-13 18:28:29 +08:00
|
|
|
}
|
2017-06-11 04:32:56 +08:00
|
|
|
}
|
2016-03-13 18:28:29 +08:00
|
|
|
}
|
|
|
|
|