src/util/events.ts
Properties |
|
Methods |
constructor()
|
Defined in src/util/events.ts:9
|
publish | |||||||||
publish(topic: string, ...args: any[])
|
|||||||||
Defined in src/util/events.ts:45
|
|||||||||
Parameters :
Returns :
[] | null
|
subscribe | |||||||||
subscribe(topic: string, handlers: EventHandler[])
|
|||||||||
Defined in src/util/events.ts:15
|
|||||||||
Parameters :
Returns :
void
|
unsubscribe | |||||||||
unsubscribe(topic: string, handler?: EventHandler)
|
|||||||||
Defined in src/util/events.ts:23
|
|||||||||
Parameters :
Returns :
boolean
|
Private c |
Default value : new Map<string, EventHandler[]>()
|
Defined in src/util/events.ts:9
|
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;
}
});
}
}