All files event.ts

100% Statements 17/17
83.33% Branches 5/6
100% Functions 6/6
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37              6x     6x     2x 2x 1x     1x   2x     2x 2x 2x     45x 45x 4x 4x         6x
/*
 * @Author: lijianzhang
 * @Date: 2018-08-29 22:38:06
 * @Last Modified by: lijianzhang
 * @Last Modified time: 2018-08-29 23:56:02
 */
 
export class Event {
    listenerMap: Map<string, Set<Function>> = new Map();
 
    on(type: string, fn: Function) {
        const set = this.listenerMap.get(type);
        if (set) {
            set.add(fn);
        } else {
            this.listenerMap.set(type, new Set([fn]));
        }
        return () => this.unListener(type, fn);
    }
 
    unListener(type: string, fn: Function) {
        const set = this.listenerMap.get(type);
        if (set) set.delete(fn);
    }
E
    emit(type: string, data: any) {
        const fns = this.listenerMap.get(type);
        if (fns) {
            fns.forEach((listener) => {
                listener(data);
            });
        }
    }
}
 
export default new Event();