Skip to content

Commit

Permalink
Build JS client code to work with the websocket/channel functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
Marta Medio committed Mar 11, 2019
1 parent 990d9b6 commit 816b881
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
31 changes: 30 additions & 1 deletion assets/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,33 @@ import "phoenix_html"
// Import local files
//
// Local files can be imported directly using relative paths, for example:
// import socket from "./socket"
import socket from "./socket"


// Connect and Join the chat channel
var channel = socket.channel('my_chat:lobby', {});
channel.join();

var ul = document.getElementById('msg-list');
var name = document.getElementById('name');
var msg = document.getElementById('msg');

// Listen for the Enter keypress event to send a new message
msg.addEventListener('keypress', function (event) {
if (event.keyCode == 13 && msg.value.length > 0) {
channel.push('shout', {
name: name.value,
message: msg.value
});
msg.value = '';
}
});

// Listen to the shout event to create a new list item for each message
channel.on('shout', function (payload) {
var li = document.createElement("li");
var name = payload.name || 'guest';
li.innerHTML = '<b>' + name + '</b>: ' + payload.message;
ul.appendChild(li);
});

4 changes: 0 additions & 4 deletions assets/js/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,5 @@ let socket = new Socket("/socket", {params: {token: window.userToken}})
socket.connect()

// Now that you are connected, you can join channels with a topic:
let channel = socket.channel("topic:subtopic", {})
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })

export default socket

0 comments on commit 816b881

Please sign in to comment.