为什么在浏览器中未定义socket.id [英] why is socket.id undefined in the browser
问题描述
如果我执行console.log(socket),则会在Firebug中获得一个套接字对象.在obj中,我可以看到带有id
的属性,并且可以看到id的值.但是当我做console.log(socket.id)时,我变得不确定.为什么?
If i do console.log(socket) i get a socket object in firebug. In the obj I could see a property with id
and i could see the value of the id. But when I do console.log(socket.id) i get undefined. why?
var socket = io();
$(document).ready( function(){
console.log(socket);
console.log(socket.id);
console.log(socket.ids);
$(".click").on("click", function(e){
alert("clicked")
socket.emit("clicked", socket.id)
$(this).addClass("removeclick");
})
});
ps我可以得到socket.ids
,它是0,但不是socket.id.
ps I could get socket.ids
which is 0 but not socket.id.
推荐答案
Socket.io需要一些时间来建立连接.我发现在客户端获取ID的最好方法是:
Socket.io needs some time for establish the connection. The best way I found to get ID on client-side is:
socket.on('connect', () => {console.log(socket.id)});
'connect'是系统事件,当连接就绪时发出.
'connect' is system event which emitting when connection is ready.
(我当前的socket.io版本是1.7.2)
(my current socket.io version is 1.7.2)
这篇关于为什么在浏览器中未定义socket.id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!