Skip to content

Instantly share code, notes, and snippets.

@renanvalentin
Created February 12, 2018 10:36
Show Gist options
  • Save renanvalentin/52d703015205d646b80986b7f13c2d4b to your computer and use it in GitHub Desktop.
Save renanvalentin/52d703015205d646b80986b7f13c2d4b to your computer and use it in GitHub Desktop.
export type Channel = {
on(event : string, listener : Function): *
};
export type Subscriber = {
listener(config : { window : HTMLIFrameElement, domain : string }): Channel
};
const subscribe = (channel : Channel) => {
let listeners = {};
let stopChannel = {};
const hasListeners = (eventName : string) : boolean => {
return listeners[eventName] && listeners[eventName].length > 0 ? true : false;
};
const addListener = (eventName : string, listener : Function) => {
listeners[eventName].push(listener);
};
const initializeChannel = (eventName : string, listener : Function) => {
listeners[eventName] = [
listener
];
stopChannel[eventName] = channel.on(eventName, (...args) => {
listeners[eventName].forEach(l => l(...args));
});
};
return {
on(eventName : string, listener : Function) : Function {
if (hasListeners(eventName)) {
addListener(eventName, listener);
} else {
initializeChannel(eventName, listener);
}
return function unsubscribe() {
const index = listeners[eventName].indexOf(listener);
listeners[eventName].splice(index, 1);
if (!hasListeners(eventName)) {
stopChannel[eventName]();
}
};
}
};
};
export function createChannel(subscriber : Subscriber, iframe : HTMLIFrameElement) : Channel {
const channel = postRobot.listener({ window: iframe.contentWindow, domain: __HOST__ });
return subscribe(channel);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment