3.5 KiB
3.5 KiB
id | title | challengeType |
---|---|---|
589fc832f9fc0f352b528e78 | Announce New Users | 2 |
Description
Change the event name to 'user' and as the data pass an object along containing fields 'name', 'currentUsers', and boolean 'connected' (to be true if connection, or false for disconnection of the user sent). Be sure to make the change to both points we had the 'user count' event and set the disconnect one to sent false for field 'connected' instead of true like the event emitted on connect.
io.emit('user', {name: socket.request.user.name, currentUsers, connected: true});
Now your client will have all the nesesary information to correctly display the current user count and annouce when a user connects or disconnects! To handle this event on the client side we should listen for 'user' and then update the current user count by using jQuery to change the text of #num-users
to '{NUMBER} users online', as well as append a <li>
to the unordered list with id 'messages' with '{NAME} has {joined/left} the chat.'.
An implementation of this could look like the following:socket.on('user', function(data){ $('#num-users').text(data.currentUsers+' users online'); var message = data.name; if(data.connected) { message += ' has joined the chat.'; } else { message += ' has left the chat.'; } $('#messages').append($('<li>').html('<b>'+ message +'<\/b>')); });Submit your page when you think you've got it right.
Instructions
Tests
tests:
- text: Event 'user' is emitted with name, currentUsers, and connected
testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /io.emit.*('|")user('|").*name.*currentUsers.*connected/gi, 'You should have an event emitted named user sending name, currentUsers, and connected'); }, xhr => { throw new Error(xhr.statusText); })
- text: Client properly handling and displaying the new data from event 'user'
testString: "getUserInput => $.get(getUserInput('url')+ '/public/client.js') .then(data => { assert.match(data, /socket.on.*('|\")user('|\")[^]*num-users/gi, 'You should change the text of #num-users within on your client within the \"user\" even listener to show the current users connected'); assert.match(data, /socket.on.*('|\")user('|\")[^]*messages.*li/gi, 'You should append a list item to #messages on your client within the \"user\" event listener to annouce a user came or went'); }, xhr => { throw new Error(xhr.statusText); })"
Challenge Seed
Solution
// solution required