M
M
matveyvarg2015-10-13 16:03:04
JavaScript
matveyvarg, 2015-10-13 16:03:04

Why is redirect only after the second click?

Client code:

$( document ).ready(function() {
   var socket = io();
   $('#create').click(function(){
      socket.emit('Create room',(socket.id).toString());
   });
   $('#join').click(function(){
   	  socket.emit('join',$('#roomID').val());	
   });
   socket.on('joined',function(){
   		window.location.replace("/room");
   });
});

Part of the code on the server:
io.on('connection', function(socket){
  socket.on('Create room', function(msg){
    socket.emit('joined');
    room_id = ( Math.random() * 100000 ) | 0;
    listOfRooms.push(room_id);
    socket.join(room_id);
    console.log('Socket '+socket.id.toString()+' was connected to room '+room_id.toString());
    Conn[socket.id.toString()]=room_id;    
    });
  });

For some reason, the redirect to '/room' goes only after two clicks on the create button. And if you hang redirect on the click itself, then it does not happen at all.
Here is the whole code: https://dropmefiles.com/gxLjL

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Shatokhin, 2015-10-13
@matveyvarg

You don't wait for the connect event. Here's an example for you:

var socket = io(); // не стоит ждать загрузки всего документа, сокет должен успеть "открыться" к событию "document ready"

socket.on('joined',function(){
  window.location.replace("/room");
});

socket.on('connect', function () { // Вот теперь emit будет работать сразу
  $( document ).ready(function() {
    $('#create').click(function(){
      socket.emit('Create room',(socket.id).toString());
    });

    $('#join').click(function(){
      socket.emit('join',$('#roomID').val());	
    });
  });	
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question