From 8a2e7de16bf03e3161ff9ea18d745d0fd0cd8deb Mon Sep 17 00:00:00 2001 From: Andi Susanto Date: Sat, 19 Nov 2016 18:04:17 +0800 Subject: [PATCH] Update online users properly --- index.html | 22 +++++++++++++++------- server.js | 5 +++++ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/index.html b/index.html index 043d48a..fef8af2 100644 --- a/index.html +++ b/index.html @@ -127,15 +127,23 @@ var userList = document.getElementById('users'); var userTemplate = document.querySelector('#templates > .list-user'); + var onlineUsers; socket.on('load connected users', function(clients) { - userList.innerHTML = ''; // gotta reset - Object.values(clients).forEach(function(user) { - var el = userTemplate.cloneNode(true); - el.dataset.id = user; - el.querySelector('.avatar').src = 'https://robohash.org/' + user + '.png?size=48x48'; - el.querySelector('p').textContent = user; - userList.appendChild(el); + onlineUsers = Object.values(clients).filter(function(user) { + return user != username; }); + userList.innerHTML = ''; // gotta reset + if (onlineUsers.length > 0) { + onlineUsers.forEach(function(user) { + var el = userTemplate.cloneNode(true); + el.dataset.id = user; + el.querySelector('.avatar').src = 'https://robohash.org/' + user + '.png?size=48x48'; + el.querySelector('p').textContent = user; + userList.appendChild(el); + }); + } else { + userList.innerHTML = 'You are never alone'; + } }); socket.on('chat message', appendChat); diff --git a/server.js b/server.js index fba54df..8e793ba 100644 --- a/server.js +++ b/server.js @@ -43,12 +43,17 @@ io.on('connection', (socket) => { socket.broadcast.emit('log', socket.username + ' has joined the chat'); if (Object.keys(clients).length == 1) { socket.emit('log', 'Don\'t worry, you are not alone!'); + } else { + // Update online user list for other users + socket.broadcast.emit('load connected users', clients); } }); socket.on('disconnect', () => { socket.broadcast.emit('log', clients[socket.id] + ' has left the chat'); delete clients[socket.id]; + // Update online user list for other users + socket.broadcast.emit('load connected users', clients); }); bot.create(function(err, session) {