import {ListenerCollection} from "./listener-collection"; import {IEvent} from "./types"; import {Collection, HashMap} from "../collection"; import {GetString, ToString} from "../utils"; import {ListenerObject} from "./listen-to"; @ToString('edde-js/event/event-bus') export class EventBus { protected listenerCollections: HashMap>; public constructor() { this.listenerCollections = new HashMap(); } /** * return listener collection for the given event * * @param event */ public listener(event: ToString): ListenerCollection { return this.listenerCollections.ensure(event.toString(), () => new ListenerCollection()); } /** * emit the given event * * @param event */ public emit(event: T): T { this.listener(GetString(event)).emit(event); return event; } /** * subscribe all events defined on the given instance * * @param instance */ public subscribe(instance: T): T { new Collection((instance)['::listeners'] || []).each(listenerProperty => { const context: any = listenerProperty.context || instance; this.listener(listenerProperty.event).add( context[listenerProperty.handler], listenerProperty.weight, context, listenerProperty.cancellable ); }); return instance; } }