From 7c5faf7e49b9204fd52bd2938388a61f0038c7e1 Mon Sep 17 00:00:00 2001 From: Robbie Antenesse Date: Thu, 3 Jan 2019 16:38:22 -0700 Subject: [PATCH] Add Current Visitors count display --- public/js/little-library.js | 4 ++++ server.js | 13 +++++-------- templates/htmlContainer.html | 12 +++++++++--- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/public/js/little-library.js b/public/js/little-library.js index 249323a..c9389f6 100644 --- a/public/js/little-library.js +++ b/public/js/little-library.js @@ -3,6 +3,10 @@ $(document).ready(function() { var downloadButton; + socket.on('update visitors', function(visitors) { + $('#visitors').text(visitors); + }); + socket.on('get book', function(url) { $(downloadButton).replaceWith('Download'); }); diff --git a/server.js b/server.js index 23a5c8d..6e5b820 100644 --- a/server.js +++ b/server.js @@ -24,6 +24,7 @@ function Server () { this.templateCache = {}; + this.connections = 0; this.takenBooks = []; this.server.use(helmet()); @@ -136,7 +137,8 @@ function Server () { }); this.io.on('connection', socket => { - this.broadcastVisitors(); + this.connections++; + this.io.emit('update visitors', this.connections); socket.on('take book', bookId => { const fileLocation = this.takeBook(bookId, socket.id); @@ -149,8 +151,8 @@ function Server () { }); socket.on('disconnect', () => { - // console.log(socket.id + ' disconnected'); - this.broadcastVisitors(); + this.connections--; + this.io.emit('update visitors', this.connections); this.deleteBooks(socket.id); }); }); @@ -276,11 +278,6 @@ Server.prototype.generateHistoryPage = function (req) { }); } -Server.prototype.broadcastVisitors = function () { - const numberConnected = this.io.of('/').clients().connected.length; - this.io.emit('connected', numberConnected); -} - Server.prototype.start = function () { this.http.listen(settings.port, () => { console.log('Started server on port ' + settings.port); diff --git a/templates/htmlContainer.html b/templates/htmlContainer.html index 5d87648..3d12840 100644 --- a/templates/htmlContainer.html +++ b/templates/htmlContainer.html @@ -20,7 +20,13 @@