
export default class EventListener {

    static handlers: { [name: string]: { handler: Function, target: any }[] } = {};

    public static on(eventName: string, handler: Function, target: any) {
        const handObj = { handler: handler, target: target };
        let handlerList = this.handlers[eventName];
        if (!handlerList) {
            handlerList = [];
            this.handlers[eventName] = handlerList;
        }
        this.handlers[eventName].push(handObj);
    }

    public static dispatchEvent(eventName: string, ...args: any[]) {
        const handlerList = this.handlers[eventName];
        if (!handlerList) return

        let i;
        let params = [];
        for (i = 1; i < arguments.length; i++) {
            params[i].push(arguments[i]);
        }

        for (i = 0; i < handlerList.length; i++) {
            const handlerObj = handlerList[i];
            if (handlerObj) {
                handlerObj.handler.apply(handlerObj.target, params);
            }
        }
    }

    public static off(eventName: string, handler: Function, target: any) {
        const handlerList = this.handlers[eventName];
        if (!handlerList) return
        for (let i = 0; i < handlerList.length; i++) {
            let handlerObj = handlerList[i];
            if (handlerObj.handler === handler && handlerObj.target == target) {
                this.handlers[eventName].splice(i, 1);
            }
        }
    }

}
