Created
June 19, 2019 14:31
-
-
Save jpbalarini/253275f97fdeac960c11720959d37da1 to your computer and use it in GitHub Desktop.
How to execute a method on rails via action cable
This file contains hidden or 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
socket = new WebSocket('ws://localhost:3000/api/v1/action_cable'); | |
const onMessage = (ws, store) => evt => { | |
let msg = JSON.parse(evt.data); | |
if (msg.type === "ping") { | |
return; | |
} | |
console.log("FROM RAILS: ", msg); | |
} | |
socket.onmessage = onMessage(socket); | |
// you need to subscribe to the channel first | |
var msg = { | |
command: 'subscribe', | |
identifier: JSON.stringify({ | |
channel: 'ReadingsChannel', | |
}), | |
}; | |
socket.send(JSON.stringify(msg)); | |
// the method foobar is going to be executed on Rails (channel file) | |
var msg = { | |
command: 'message', | |
identifier: JSON.stringify({ | |
channel: 'ReadingsChannel', | |
}), | |
data: JSON.stringify({ | |
action: 'foobar', | |
code: 1234 | |
}), | |
}; | |
socket.send(JSON.stringify(msg)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment