File

src/util/events.ts

Index

Properties
  • Private c
Methods

Constructor

constructor()

Methods

publish
publish(topic: string, ...args: any[])
Parameters :
Name Type Optional
topic string No
args any[] No
Returns : [] | null
subscribe
subscribe(topic: string, handlers: EventHandler[])
Parameters :
Name Type Optional
topic string No
handlers EventHandler[] No
Returns : void
unsubscribe
unsubscribe(topic: string, handler?: EventHandler)
Parameters :
Name Type Optional
topic string No
handler EventHandler Yes
Returns : boolean

Properties

Private c
Default value : new Map<string, EventHandler[]>()
import { Injectable } from '@angular/core';

export type EventHandler = (...args: any[]) => any;

@Injectable({
    providedIn: 'root',
})
export class Events {
    private c = new Map<string, EventHandler[]>();

    constructor() {
        console.log('events.ts');       
    }

    subscribe(topic: string, ...handlers: EventHandler[]) {
        let topics = this.c.get(topic);
        if (!topics) {
            this.c.set(topic, topics = []);
        }
        topics.push(...handlers);
    }

    unsubscribe(topic: string, handler?: EventHandler): boolean {
        if (!handler) {
            return this.c.delete(topic);
        }

        const topics = this.c.get(topic);
        if (!topics) {
            return false;
        }

        const index = topics.indexOf(handler);

        if (index < 0) {
            return false;
        }
        topics.splice(index, 1);
        if (topics.length === 0) {
            this.c.delete(topic);
        }
        return true;
    }

    publish(topic: string, ...args: any[]): any[] | null {
        const topics = this.c.get(topic);
        if (!topics) {
            return null;
        }
        return topics.map(handler => {
            try {
                return handler(...args);
            } catch (e) {
                console.error(e);
                return null;
            }
        });
    }
}

results matching ""

    No results matching ""