Answer the question
In order to leave comments, you need to log in
Emit doesn't work correctly, how to fix it?
// При логине
client.on('new user', function(name) {
module.checkUser(name, function(err, user) {
console.log(user);
client.username = user.name;
client.id = user._id;
client.room = user.currentRoom;
var toMe = 'you joined to the room [' + user.currentRoom + ']';
var toRoom = user.name + ' has connected to this room [' + user.currentRoom + ']';
var messageToClient = new messageItem(user.name, user.currentRoom, toMe);
var messageToRoom = new messageItem(user.name, user.currentRoom, toRoom);
console.log(messageToClient);
client.emit('to chat', messageToClient); // отправляет только мне
client.to(user.currentRoom).emit('to chat', messageToRoom); // должно отправлять всем в комнату
//кроме меня но отправляет и мне, подскажите чё не так
});
});
// Код модуля который проверяет есть ли такой пользователь
var users = require('../models/model.User.js');
var messages = require('../models/model.messages.js');
var checkUser = function(name, callback) {
users.findOne({name: name}, function(err, user) {
if (user) {
console.log('user [' + user.name + '] found');
callback(null, user);
return;
}
var userObj = {
name: name,
currentRoom: 'room1'
};
new users(userObj).save(function(err, createdUser) {
if (err) {
console.log(err);
callback(null);
return;
}
console.log('created new user: [' + user.name + ']');
callback(null, createdUser);
});
});
};
module.exports = {
checkUser: checkUser
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question