Skip to content

Instantly share code, notes, and snippets.

@xuorig
Created May 29, 2016 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuorig/b167b27f75c149b8da5837b79585169f to your computer and use it in GitHub Desktop.
Save xuorig/b167b27f75c149b8da5837b79585169f to your computer and use it in GitHub Desktop.
// Sample ActionCable ES6 client
//
// To be used like:
//
// const myEventHandlerFunction = (event) => {
// console.log(event.message);
// }
//
// ActionCableClient.connect(
// 'ws://localhost:3000/cable',
// 'YourChannel',
// myEventHandlerFunction
// ).then(client => {
// client is guaranteed to be initialized properly
// when promise is resolved.
// })
export default class ActionCableClient {
constructor(uri, channel, onMessage) {
this.uri = uri;
this.channel = channel;
this.onMessage = onMessage;
this.socket = new WebSocket(uri);
this.socket.onmessage = this._handleMessage.bind(this);
this._onReadyPromise = new Promise((resolve, reject) => {
this._resolveOnReady = resolve;
this._rejectOnReady= reject;
});
}
static connect(uri, channel, onMessage) {
const instance = new this(uri, channel, onMessage);
return instance.connect();
}
connect() {
this.socket.onopen = () => {
this.socket.send(this._getSubscribePayload())
};
return this._onReadyPromise;
}
_handleMessage(event) {
const msg = JSON.parse(event.data);
if (msg.type === 'confirm_subscription') {
this._resolveOnReady(this);
} else {
this.onMessage(msg);
}
}
_getSubscribePayload() {
return JSON.stringify({
command: 'subscribe',
identifier: JSON.stringify({
channel: this.channel
})
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment