Skip to content

Instantly share code, notes, and snippets.

@cvan
Created May 27, 2015 22:09
Show Gist options
  • Save cvan/c0b7e2b7529f0350f0c8 to your computer and use it in GitHub Desktop.
Save cvan/c0b7e2b7529f0350f0c8 to your computer and use it in GitHub Desktop.
wrapper class for BroadcastChannel
class FrameMessenger {
constructor(name) {
this._listeners = {};
this.name = name || 'frame';
this.bc = new BroadcastChannel(this.name);
this.bc.addEventListener('message', e => {
if (e.data && typeof e.data === 'object' && e.data.type) {
this.emit(e.data.type, e.data.data);
}
});
}
emit(name, ...args) {
(this._listeners[name] || []).forEach(func => func.apply(this, args));
return this;
}
on(name, func) {
if (name in this._listeners) {
this._listeners[name].push(func);
} else {
this._listeners[name] = [func];
}
return this;
}
off(name) {
if (name) {
this._listeners[name] = [];
} else {
this._listeners = {};
}
return this;
}
send(type, data) {
this.bc.postMessage({
type: type,
data: data
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment