Practice exercises CHAPTER 10 433
- Add the updateUserList function.
This function is called when the chat service sends an updated user list. - Add code to clear the existing user list and repopulate the list.
The updateUserList function should look like the following.
function updateUserList(data) {
$('#users').empty();
$.each(data, function (key, value) {
$('#users').append('' + key + '');
});
} - Add the sendMessage function.
This function is called to send a message to the chat service. The sendMessage func-
tion should look like the following.
function sendMessage() {
var message = $('#data').val();
$('#data').val('');
socket.emit('sendchat', message);
$('#data').focus();
} - Add the processEnterPress function.
This function is called when the user presses the Enter key. The processEnterPress func-
tion should look like the following.
function processEnterPress(e) {
if (e.which == 13) {
e.preventDefault();
$(this).blur();
$('#datasend').focus().click();
}
} - Review the code.
The completed default.js file is as follows.
///
var socket;
$(document).ready(function () {
socket = io.connect('http://localhost:8080');
socket.on('connect', addUser);
socket.on('updatechat', processMessage);
socket.on('updateusers', updateUserList);
$('#datasend').click(sendMessage);
$('#data').keypress(processEnterPress);
});