I've read a few questions here on SO about this subject, but I'm not sure yet how to solve it in my case. The getMsgs
emit event is firing as many times as I've accessed the /admin
url. I know from other questions on SO that it is because the listener is registering every time I visit the admin
page, but I'm not sure how to refactor my code (ie where to move the io.on(..)
and how to call it from the router.get('/admin'..)
function.
router.get('/admin', function(req, res, next){
io.on('connection', function (socket) {
dal.findAllMessages(function(err, messages) {
console.log('sent msgs');
socket.emit('getMsgs', messages);
});
socket.on('newMsg', function(data){
console.log('newMsg');
console.log(data);
dal.addMessage(data);
dal.findAllMessages(function(err, messages) {
socket.emit('getMsgs', messages);
});
});
socket.on('delMsg', function(data){
console.log('delMsg');
console.log(data);
dal.deleteMessage(data);
dal.findAllMessages(function(err, messages) {
socket.emit('getMsgs', messages);
});
});
});
res.render('admin');
});