Created
May 27, 2015 22:09
-
-
Save cvan/c0b7e2b7529f0350f0c8 to your computer and use it in GitHub Desktop.
wrapper class for BroadcastChannel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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