Created
May 29, 2016 18:31
-
-
Save xuorig/b167b27f75c149b8da5837b79585169f to your computer and use it in GitHub Desktop.
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
// 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