socket.io on method callback-Collection of common programming errors
server.js
socket.on('adduser', username, successcallback){
if(users.hasOwnProperty(username)){
} else {
socket.username = username;
users[username] = { name: username };
socket.emit('updatechat', 'SERVER', 'you have connected');
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
io.sockets.emit('updateusers', users);
successcallback({ msg: 'User ' + username + ' has been successfully added' });
}
});
index.html
socket.on('connect', function(){
var username = prompt('Whats your name?');
socket.emit('adduser', username, function(data){
console.log(data);
});
});
This makes my app crash. Isn’t this how a callback should be implemented?
-
The definition of the adduser message handler is missing a
function(...)
. It should be:socket.on('adduser', function(username, successcallback) { ... });