eventManager.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { EventCallback, TemplateManager } from "./templateManager";
  2. export class EventManager {
  3. private callbacksContainer: { [key: string]: Array<{ eventType?: string, selector?: string, callback: (eventData: EventCallback) => void }> }
  4. constructor(private templateManager: TemplateManager) {
  5. this.callbacksContainer = {};
  6. this.templateManager.onEventTriggered.add(eventData => {
  7. this.eventTriggered(eventData);
  8. })
  9. }
  10. public registerCallback(templateName: string, callback: (eventData: EventCallback) => void, eventType?: string, selector?: string) {
  11. if (!this.callbacksContainer[templateName]) {
  12. this.callbacksContainer[templateName] = [];
  13. }
  14. this.callbacksContainer[templateName].push({
  15. eventType: eventType,
  16. callback: callback
  17. });
  18. }
  19. public unregisterCallback(templateName: string, callback?: (eventData: EventCallback) => void, eventType?: string, selector?: string) {
  20. let callbackDefs = this.callbacksContainer[templateName] || [];
  21. this.callbacksContainer[templateName] = callbackDefs.filter(callbackDef => (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector));
  22. }
  23. private eventTriggered(data: EventCallback) {
  24. let templateName = data.template.name;
  25. let eventType = data.event.type;
  26. let selector = data.selector;
  27. let callbackDefs = this.callbacksContainer[templateName] || [];
  28. callbackDefs.filter(callbackDef => (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector)).forEach(callbackDef => {
  29. callbackDef.callback(data);
  30. });
  31. }
  32. }