Moving the channel functionality to show

The next step in polishing up our application is moving our channel logic to instead be poll-specific instead of all sitting in the lobby. Open up show.html.eex and change the template to include the WebSocket-specific code that used to live in index.html.eex. We'll need to modify it slightly as well since we'll need to have a way to tell JavaScript what poll ID it needs to use to find the right topic:

<i id="enable-polls-channel" data-poll-id="<%= @poll.id %>"></i>
<button id="polls-ping" class="btn btn-primary">Ping Websocket</button>

We'll also need to open up socket.js and change the code to start using this new code. Modify the old if statement that checked if polls were enabled for that page to instead grab the enable socket tag:

// ...

// Only connect to the socket if the polls channel actually exists!
const enableSocket = document.getElementById('enable-polls-channel');
if (enableSocket) {
// Pull the Poll Id to find the right topic from the data attribute
const pollId = enableSocket.getAttribute('data-poll-id');
// Create a channel to handle joining/sending/receiving
const channel = socket.channel('polls:' + pollId, {});

// ...

If we take a look over at our server we're probably going to start seeing a lot of warnings in our terminal:

[warn] Ignoring unmatched topic "polls:1" in VocialWeb.UserSocket

This is good! This tells us that our JavaScript code is actually working and doing everything we expect it to! Now we need to change our socket and channel code to use these new topics, which means we're going to be working with topic wildcards now! Open up lib/vocial_web/channels/user_socket.ex and change the polls channel line to use a wildcard instead of "lobby" as the subtopic:

channel "polls:*", VocialWeb.PollsChannel

Finally, hop over to lib/vocial_web/channels/polls_channel.ex and change our join function to be able to listen for this new wildcard:

def join("polls:" <> _poll_id, _payload, socket) do
{:ok, socket}
end

That will be it! Our functionality now should be otherwise unchanged from what we had before, except it will be much more specific to that specific poll. This will enable us to be able to do fun things with charts and graphs later on, as well as implementing features and functionality like live chat on each of the polls!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset