JavaScript Client
Let’s have a look at the JavaScript client messages in depth.
We'll cover the following...
Receiving messages with the JavaScript client
A Channel can send messages to a connected client at any time, not just in response to an incoming message. We coded this earlier in our PingChannel with handle_out/3. We’ll leverage this message to request that the connected client sends us a ping.
The callback of our client channel is used to register incoming message subscriptions. The first argument is the string name of the event that we want to handle; this requires us to know the exact event name for incoming messages. For this reason, it is a good idea not to use dynamic event names. We can instead place dynamic information in the message payload.
As we did earlier, we use the broadcast/3 function to request a ping from our Channel. This will cause a message to be pushed to all connected clients on the ping topic. Our handle_out function changes the original request_ping payload into a different message. We can see the final result in the developer console.
Try loading multiple instances of the web page and broadcasting again. We will see that every connected client receives the broadcast. This makes broadcasting a powerful way to send data to all ...