Skip to content

Instantly share code, notes, and snippets.

@caiguanhao
Created November 29, 2017 03:45
Show Gist options
  • Save caiguanhao/01944f39aa4ec951e6de50d92b2c835d to your computer and use it in GitHub Desktop.
Save caiguanhao/01944f39aa4ec951e6de50d92b2c835d to your computer and use it in GitHub Desktop.
action_cable for wx
class Cable {
constructor(options) {
this.options = options || {}
this.polled = 0
wx.onSocketOpen(() => {
if (this.options.connected) {
this.options.connected()
}
this.resubscribe()
this.stopPolling()
this.polled = 0
})
wx.onSocketError(() => {
this.startPolling()
})
wx.onSocketClose(() => {
if (this.options.disconnected) {
this.options.disconnected()
}
this.startPolling()
})
wx.onSocketMessage(res => {
let data = JSON.parse(res.data)
let subscription = this.subscriptions[data.identifier]
if (subscription) subscription.received(data)
})
}
connect(url) {
this.options.url = url || this.options.url
wx.connectSocket({
url: this.options.url
})
}
startPolling() {
this.stopPolling()
this.poll()
}
stopPolling() {
clearTimeout(this.pollTimeout)
}
poll() {
this.polled++
this.pollTimeout = setTimeout(() => {
this.connect()
}, Math.min(2000, 500 * this.polled));
}
subscriptions = {}
subscribe(info, options) {
let identifier = JSON.stringify(info)
let subscription = new Subscription(identifier, options)
this.subscriptions[identifier] = subscription
subscription.sendCommand('subscribe')
subscription.unsubscribe = () => {
subscription.sendCommand('unsubscribe');
this.subscriptions[identifier] = null
delete this.subscriptions[identifier]
}
return subscription
}
resubscribe() {
for (let identifier in this.subscriptions) {
let subscription = this.subscriptions[identifier]
if (subscription) {
subscription.sendCommand('subscribe')
}
}
}
}
class Subscription {
constructor(identifier, options) {
this.identifier = identifier
this.options = options
}
sendCommand(command, data) {
let content = {
command: command,
identifier: this.identifier
}
if (data) content.data = data;
wx.sendSocketMessage({ data: JSON.stringify(content) })
}
unsubscribe() {}
send(content) {
this.sendCommand('message', JSON.stringify(content))
}
received(data) {
if (data.type === 'confirm_subscription' && this.options.subscribed) {
this.options.subscribed()
} else if (this.options.received) {
this.options.received(data.message);
}
}
}
module.exports = Cable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment