Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 10 433



  1. Add the updateUserList function.
    This function is called when the chat service sends an updated user list.

  2. 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 + '
    ');
    });
    }

  3. 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();
    }

  4. 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();
    }
    }

  5. 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);
});
Free download pdf