We’ve been using WebComponents a lot lately at our place of work and sadly using the phoenix socket library threaded through everything is not very reusable, so ended up making a webcomponent of the phoenix socket itself. So we can just do something like this in html:
<phoenix-socket
endpoint="/socket"
param-token="<%= Guardian.Plug.current_token(@conn) %>"
connected="{{socketConnected}}"
socket="{{socket}}"
connect
></phoenix-socket>
EndPoint: "[[socket.endPoint]]"<br />
IsConnected: "[[socketConnected]]"<br />
And this, in this case, outputs this to the screen:
EndPoint: "/socket/websocket"
IsConnected: "true"
Of course changing any of the properties like endpoint or parameters or disabling ‘connect’ or so will cause it to disconnect and/or reconnect with new parameters, but for a socket that is a rare case anyway.
We can continue to thread to join a topic like:
<phoenix-channel
socket="{{socket}}"
channel="{{channel}}"
topic-pre="Messenger:"
topic="system"
msg-joined="{{msgJoined}}"
connected="{{topicSystemConnected}}"
></phoenix-channel>
System Topic Joined: [[topicSystemConnected]] <br />
Your nick: [[msgJoined.nick]]
Which outputs this (since the server "Messenger:system"
topic returns a structure that contains your nick
):
System Topic Joined: true
Your nick: Gabriel Robertson
The {{socket}}
here is the same variable that is from the <phoenix-socket />
, you can pass in the normal Phoenix library socket object as well if you are using an existing library elsewhere and want to re-use the socket, or you can take this socket and give it to normal javascript code elsewhere. And as expected if you add a sleep
or something to the socket join then the ‘true’ above will be ‘false’ until the join finally goes through. It automatically handles new sockets, no sockets, sockets losing and reconnecting its connection, etc… Also handles changing properties will disconnect and reconnect to a new given topic with whatever parameters are specified as expected. You can get various topic information here (like with the socket, the channel has a lot more options that are not demonstrated here, still need to program in more as well).
To handle messages you can use javascript to listen as normal, or continue using html by doing:
<phoenix-msghandler
channel="{{channel}}"
key="msg:recv"
msg="{{receivedMsg}}"
></phoenix-msghandler>
And similar for presence as well, takes the channel output from the above <phoenix-channel />
as input, or feel free to pass in your own channel object via javascript. Usual property stuff. Etc…
Do many other people use webcomponents here and might find these useful?