JSFiddle - React, Tailwind, and code Playground
Babel + JSX
/**
* Creates a new PubSubClass.
* @class
*/
class PubSubClass {
/**
* @constructs PubSubClass
*/
constructor() {
this.channels = {};
this.crossTabEnabled = false;
this.id = this._uuid();
}
/**
* Generate uuid.
* @function _uuid
* @returns {string} - returns new uuid
*/
_uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
/**
* Enable cross tab communication
* @function enableCrossTab
*/
enableCrossTab() {
if (window) {
this.crossTabEnabled = true;
}
}
/**
* Join a channel
* @function join
* @param {string} channel - the channel to join
* @param {function} handler - the function to send messages to.
*/
join(channel, handler) {
const uuid = this._uuid();
handler(false, uuid);
// If the channel doesn't exist, create it.
if (!this.channels[channel]) {
this.channels[channel] = {
clients: {},
history: []
};
}
if (this.crossTabEnabled) {
window.addEventListener('storage', (e) => {
if (e.key === `PubSub-${channel}`) {
let payload = JSON.parse(e.newValue);
if (payload.id != this.id) {
handler(payload.message, uuid);
}
}
}, false);
}
// Add our new client
this.channels[channel].clients[uuid] = handler;
return this;
}
/**
* Leave a channel
* @function leave
* @param {string} channel - the channel to leave
* @param {string} uuid - the uuid of the client who should leave
* @returns {promise} - returns new promise, resolved when client leaves
*/
leave(channel, uuid) {
return new Promise(resolve => {
// Once we leave a channel, set our handler to a noop.
this.channels[channel].clients[uuid] = () => {/*noop*/};
resolve();
});
}
/**
* Publish a...