all files / common/global-event/ global-event.service.ts

100% Statements 23/23
50% Branches 2/4
100% Functions 6/6
100% Lines 20/20
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                                                   
/*
 *  @license
 *  Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
 *
 *  Use of this source code is governed by an Apache-2.0 license that can be
 *  found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
 */
 
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { GlobalEventEmmitter } from './global-event-emmitter';
 
@Injectable()
export class GlobalEventService {
    private globalEventEmmitter: GlobalEventEmmitter;
    private listeners$ = {} as {[index: string]: Observable<any>};
    private listenersFn$ = {} as { [index: string]: (params?: any[]) => void };
 
    constructor() {
        this.globalEventEmmitter = GlobalEventEmmitter.instance;
    }
 
    public register(event: string) {
        Eif (!this.listeners$[event]) {
            this.listeners$[event] = new Observable<any[]>(observer => {
                this.listenersFn$[event] = (params: any[]) => {
                    // console.log('message received: ' + event + '  params: ' + params[0]);
                    observer.next(params);
                };
                this.globalEventEmmitter.on(event, this.listenersFn$[event]);
            });
        }
 
        return this.listeners$[event];
    }
 
    public unregister(event: string) {
        Eif (this.listeners$[event]) {
            this.globalEventEmmitter.off(event, this.listenersFn$[event]);
            this.listeners$[event] = undefined;
            this.listenersFn$[event] = undefined;
        }
    }
}