-
Notifications
You must be signed in to change notification settings - Fork 96
/
app.js
42 lines (35 loc) · 1.69 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// We need to import the CSS so that webpack will load it.
// The MiniCssExtractPlugin is used to separate it out into
// its own CSS file.
import "../css/app.scss"
// webpack automatically bundles all modules in your
// entry points. Those entry points can be configured
// in "webpack.config.js".
//
// Import deps with the dep name or local files with a relative path, for example:
//
// import {Socket} from "phoenix"
import socket from "./socket"
//
import "phoenix_html"
let channel = socket.channel('room:lobby', {}); // connect to chat "room"
channel.on('shout', function (payload) { // listen to the 'shout' event
let li = document.createElement("li"); // create new list item DOM element
let name = payload.name || 'guest'; // get name from payload or set default
li.innerHTML = '<b>' + name + '</b>: ' + payload.message; // set li contents
ul.appendChild(li); // append to list
});
channel.join(); // join the channel.
let ul = document.getElementById('msg-list'); // list of messages.
let name = document.getElementById('name'); // name of message sender
let msg = document.getElementById('msg'); // message input field
// "listen" for the [Enter] keypress event to send a message:
msg.addEventListener('keypress', function (event) {
if (event.keyCode == 13 && msg.value.length > 0) { // don't sent empty msg.
channel.push('shout', { // send the message to the server on "shout" channel
name: name.value, // get value of "name" of person sending the message
message: msg.value // get message text (value) from msg input field.
});
msg.value = ''; // reset the message input field for next message.
}
});