1 declare const window: Window;
3 export class BasePubSub {
5 subscribers: Map<string, ISubscriber>;
6 eventsCallbacks: Array<Function>;
8 eventsToWait: Map<string, Array<string>>;
9 lastEventNotified: string;
11 constructor(pluginId: string) {
12 this.subscribers = new Map<string, ISubscriber>();
13 this.eventsCallbacks = [];
14 this.eventsToWait = new Map<string, Array<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 let 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 let 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 let subscribersToNotify = Array.from(this.subscribers.keys());
69 const checkNotifyComplete = (subscriberId: string) => {
71 let 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) && this.eventsToWait.get(subscriberId).indexOf(eventType) !== -1) {
82 const actionCompletedFunction = (eventData, subId = subscriberId) => {
83 if (eventData.type == "ACTION_COMPLETED") {
84 checkNotifyComplete(subId);
86 this.off(actionCompletedFunction);
89 this.on(actionCompletedFunction);
92 checkNotifyComplete(subscriberId);
103 public isWaitingForEvent(eventName: string) : boolean {
104 return Array.from(this.eventsToWait.values()).some((eventsList: Array<string>) =>
105 eventsList.indexOf(eventName) !== -1
109 protected onMessage(event: any) {
110 if (this.subscribers.has(event.data.originId)) {
111 this.eventsCallbacks.forEach((callback: Function) => {
112 callback(event.data, event);
118 export interface IPubSubEvent {
124 export interface ISubscriber {