blob: ca313b15f56264812b5025d55fda486913256458 [file] [log] [blame]
Idan Amit71904f22018-02-13 10:38:16 +02001declare const window: Window;
2
3export class BasePubSub {
4
5 subscribers: Map<string, ISubscriber>;
6 eventsCallbacks: Array<Function>;
7 clientId: string;
8
9 constructor(pluginId: string) {
10 this.subscribers = new Map<string, ISubscriber>();
11 this.eventsCallbacks = new Array<Function>();
12 this.clientId = pluginId;
13 this.onMessage = this.onMessage.bind(this);
14
15 window.addEventListener("message", this.onMessage);
16 }
17
18 public register(subscriberId: string, subscriberWindow: Window, subscriberUrl: string) {
19 const subscriber = {
20 window: subscriberWindow,
21 locationUrl: subscriberUrl || subscriberWindow.location.href
22 } as ISubscriber;
23
24 this.subscribers.set(subscriberId, subscriber);
25 }
26
27 public unregister(subscriberId: string) {
28 this.subscribers.delete(subscriberId);
29 }
30
31 public on(callback: Function) {
32 this.eventsCallbacks.push(callback);
33 }
34
35 public off(callback: Function) {
36 let index = this.eventsCallbacks.indexOf(callback);
37 this.eventsCallbacks.splice(index, 1)
38 }
39
Idan Amitf97bae32018-03-06 13:52:58 +020040 public notify(eventType:string, eventData?:any) {
Idan Amit71904f22018-02-13 10:38:16 +020041 let eventObj = {
42 type: eventType,
43 data: eventData,
44 originId: this.clientId
45 } as IPubSubEvent;
46
47 this.subscribers.forEach( (subscriber: ISubscriber, id: string) => {
48 subscriber.window.postMessage(eventObj, subscriber.locationUrl)
49 });
50 }
51
52 protected onMessage(event: any) {
53 if (this.subscribers.has(event.data.originId)) {
54 this.eventsCallbacks.forEach((callback: Function) => {
55 callback(event.data, event);
56 })
57 }
58 }
59}
60
61export class PluginPubSub extends BasePubSub {
62
Idan Amitf97bae32018-03-06 13:52:58 +020063 constructor(pluginId: string, parentUrl: string) {
Idan Amit71904f22018-02-13 10:38:16 +020064 super(pluginId);
Idan Amitf97bae32018-03-06 13:52:58 +020065 this.register('sdc-hub', window.parent, parentUrl);
Idan Amit71904f22018-02-13 10:38:16 +020066 this.subscribe();
67 }
68
69 public subscribe() {
70 const registerData = {
71 pluginId: this.clientId
72 };
73
74 this.notify('PLUGIN_REGISTER', registerData);
75 }
76
77 public unsubscribe() {
78 const unregisterData = {
79 pluginId: this.clientId
80 };
81
82 this.notify('PLUGIN_UNREGISTER', unregisterData);
83 }
84}
85
86export interface IPubSubEvent {
87 type: string;
88 originId: string;
89 data: any;
90}
91
92export interface ISubscriber {
93 window: Window;
94 locationUrl: string;
95}