1 declare const window: Window;
3 export class BasePubSub {
5 subscribers: Map<string, ISubscriber>;
6 eventsCallbacks: Function[];
8 eventsToWait: Map<string, string[]>;
9 lastEventNotified: string;
11 constructor(pluginId: string) {
12 this.subscribers = new Map<string, ISubscriber>();
13 this.eventsCallbacks = [];
14 this.eventsToWait = new Map<string, string[]>();
15 this.clientId = pluginId;
16 this.lastEventNotified = '';
17 this.onMessage = this.onMessage.bind(this);
19 window.addEventListener('message', this.onMessage);
22 public register(subscriberId: string, subscriberWindow: Window, subscriberUrl: string) {
24 window: subscriberWindow,
25 locationUrl: subscriberUrl || subscriberWindow.location.href
28 this.subscribers.set(subscriberId, subscriber);
31 public unregister(subscriberId: string) {
32 this.subscribers.delete(subscriberId);
35 public on(callback: Function) {
36 const functionExists = this.eventsCallbacks.find((func: Function) => {
37 return callback.toString() === func.toString();
40 if (!functionExists) {
41 this.eventsCallbacks.push(callback);
45 public off(callback: Function) {
46 const index = this.eventsCallbacks.indexOf(callback);
47 this.eventsCallbacks.splice(index, 1);
50 public notify(eventType: string, eventData?: any) {
54 originId: this.clientId
57 this.subscribers.forEach( (subscriber: ISubscriber, subscriberId: string) => {
58 subscriber.window.postMessage(eventObj, subscriber.locationUrl);
61 this.lastEventNotified = eventType;
64 subscribe: function(callbackFn) {
66 if (this.subscribers.size !== 0) {
67 const subscribersToNotify = Array.from(this.subscribers.keys());
69 const checkNotifyComplete = (subscriberId: string) => {
71 const index = subscribersToNotify.indexOf(subscriberId);
72 subscribersToNotify.splice(index, 1);
74 if (subscribersToNotify.length === 0) {
79 this.subscribers.forEach((subscriber: ISubscriber, subscriberId: string) => {
80 if (this.eventsToWait.has(subscriberId) &&
81 this.eventsToWait.get(subscriberId).indexOf(eventType) !== -1) {
83 const actionCompletedFunction = (actionCompletedEventData, subId = subscriberId) => {
84 if (actionCompletedEventData.type === 'ACTION_COMPLETED') {
85 checkNotifyComplete(subId);
87 this.off(actionCompletedFunction);
90 this.on(actionCompletedFunction);
92 checkNotifyComplete(subscriberId);
102 public isWaitingForEvent(eventName: string): boolean {
103 return Array.from(this.eventsToWait.values()).some((eventsList: string[]) =>
104 eventsList.indexOf(eventName) !== -1
108 protected onMessage(event: any) {
109 if (this.subscribers.has(event.data.originId)) {
110 this.eventsCallbacks.forEach((callback: Function) => {
111 callback(event.data, event);
117 export interface IPubSubEvent {
123 export interface ISubscriber {