App > Stop listening to socket events

This commit is contained in:
brunosimon
2019-06-05 23:36:59 +02:00
parent 2a9a4ca2e1
commit 6338fc8ac8
6 changed files with 95 additions and 37 deletions
+36 -15
View File
@@ -30,8 +30,9 @@ class Chat
// Create a channel for this specific chat
this.chatSocket = this.config.socket.of('/project/' + this.slug + '/chat')
// Connection event
this.chatSocket.on('connection', (socket) =>
// Callbacks
this.socketCallbacks = {}
this.socketCallbacks.connection = (socket) =>
{
// Create user
const user = this.createUser()
@@ -49,8 +50,10 @@ class Chat
broadcastUser.color = user.color
socket.emit('user', broadcastUser)
// On message
socket.on('message', (data) =>
const userSocketCallbacks = {}
userSocketCallbacks.message = (data) =>
{
// Add ID and save
data.id = ids.getId()
@@ -74,10 +77,9 @@ class Chat
{
console.log(`${chalk.green.bold('chat > socket')} - ${chalk.cyan('message')} - ${chalk.cyan(user.name)} - ${chalk.cyan(data.text)}`)
}
})
}
// On update user
socket.on('update_user', (data) =>
userSocketCallbacks.updateUser = (data) =>
{
const newName = data.name.trim()
const oldName = user.name
@@ -96,10 +98,9 @@ class Chat
{
console.log(`${chalk.green.bold('chat > socket')} - ${chalk.cyan('update_user')} - ${chalk.cyan(oldName + ' > ' + user.name)}`)
}
})
}
// On alert
socket.on('alert', () =>
userSocketCallbacks.alert = () =>
{
// Transfer to the watcher socket
this.watcherSocket.emit('alert')
@@ -109,14 +110,28 @@ class Chat
{
console.log(`${chalk.green.bold('chat > socket')} - ${chalk.cyan('alert')} - ${chalk.cyan(user.name)}`)
}
})
}
// On disconnect
socket.on('disconnect', () =>
userSocketCallbacks.disconnect = () =>
{
// Stop listening
socket.off('message', userSocketCallbacks.message)
socket.off('update_user', userSocketCallbacks.updateUser)
socket.off('alert', userSocketCallbacks.alert)
socket.off('disconnect', userSocketCallbacks.disconnect)
console.log(`${chalk.green.bold('chat > socket')} - ${chalk.cyan('disconnect')} - ${chalk.cyan(user.name)}`)
})
})
}
// On message
socket.on('message', userSocketCallbacks.message)
socket.on('update_user', userSocketCallbacks.updateUser)
socket.on('alert', userSocketCallbacks.alert)
socket.on('disconnect', userSocketCallbacks.disconnect)
}
// Connection event
this.chatSocket.on('connection', this.socketCallbacks.connection)
}
createUser()
@@ -261,6 +276,12 @@ class Chat
this.chatSocket.emit('message', broadcastMessage)
}, 1500)
}
destructor()
{
// Stop listening
this.chatSocket.off('connection', this.socketCallbacks.connection)
}
}
module.exports = Chat