All files / mframejs/utils eventAggregator.ts

20% Statements 2/10
100% Branches 0/0
25% Functions 1/4
25% Lines 2/8

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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64            29x         29x                                                                                                        
 
 
/**
 * simple event aggregator for sending messages between components/attributes etc
 *
 */
export class EventAggregator {
 
    private channels: any;
 
    constructor() {
        this.channels = {};
    }
 
 
    // todo, do we want a async option ?
    // todo, do we want to upper/lower case all channels? less chance for typos..
 
    /**
     * publish to channel
     *
     */
    public publish(channel: string, ...args: any[]): void {
        if (Array.isArray(this.channels[channel])) {
            for (let i = 0, len = this.channels[channel].length; i < len; i++) {
                this.channels[channel][i].apply(this, args);
            }
        } else {
            // if no one is listening then do we really need to do anything ?
        }
    }
 
 
 
    /**
     * unsubscribes to channel
     *
     */
    public unsubscribe(channel: string, func: Function): void {
        if (Array.isArray(this.channels[channel])) {
            for (let i = 0, len = this.channels[channel].length; i < len; i++) {
                if (this.channels[channel][i] === func) {
                    this.channels[channel].splice(i, 1);
                }
            }
        } else {
            // channel does not exist, great!
        }
 
    }
 
 
    /**
     * subscribes to channel
     *
     */
    public subscribe(channel: string, func: Function): void {
        if (!Array.isArray(this.channels[channel])) {
            this.channels[channel] = [];
        }
        this.channels[channel].push(func);
    }
}