Commit d289d3c0 authored by dm171558's avatar dm171558

Added message functionality

* Sending message to all users in the channel
* Receiving messages from other users
parent 3cc2bcb9
......@@ -27,7 +27,7 @@ $(function() {
// When the client hits ENTER on their keyboard
if (event.which === 13) {
if (username) {
sendMessage();
} else {
setUsername();
}
......@@ -66,6 +66,25 @@ $(function() {
log(message);
}
// Sending and receiving messages
// Sends a chat message
function sendMessage () {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
message = cleanInput(message);
// if there is a non-empty message and a socket connection
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
// tell server to execute 'new message' and send along one parameter
socket.emit('newMessage', message);
}
}
// Helper methods
// Log a message
......@@ -74,6 +93,22 @@ $(function() {
addMessageElement($el, options);
}
// Adds the visual chat message to the message list
function addChatMessage (data, options) {
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// Adds a message element to the messages and scrolls to the bottom
// el - The element to add as a message
// options.fade - If the element should fade-in (default = true)
......@@ -176,4 +211,9 @@ $(function() {
socket.on('reconnect_error', function () {
log('attempt to reconnect has failed');
});
// Whenever the server emits 'new message', update the chat body
socket.on('newMessage', function (data) {
addChatMessage(data);
});
});
......@@ -51,6 +51,15 @@ export class WebSocket
});
}
});
// when the client emits 'new message', this listens and executes
socket.on('newMessage', (data) => {
// we tell the client to execute 'new message'
socket.broadcast.emit('newMessage', {
username: socket.username,
message: data
});
});
});
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment