简体   繁体   English

事件未在socket.on('connect',event)上调用

[英]event not being called on socket.on('connect', event)

I'm having an issue with socket.io, at least I think, where a function in my client code is not being called on socket.on('connect', onsocketConnected); 至少在我看来,socket.io存在问题,即我的客户端代码中的函数未在socket.on('connect', onsocketConnected);socket.on('connect', onsocketConnected);

However, if I put a conditional such as: 但是,如果我输入一个条件,例如:

if(socket.connect) {
    onsocketConnected();
}  

Then my function gets called. 然后我的函数被调用。 Also I just realized if I write it like 我也意识到我写的像
socket.on('connect', onsocketConnected()); that my function gets called correctly. 我的函数被正确调用。 My question is, upon a connection from the client to a server, is connect a value that is automatically supplied to the client? 我的问题是,从客户端到服务器的连接是否连接了自动提供给客户端的值? Looking at the documentation at https://socket.io/docs/client-api/ it states it should work as socket.on(event, callback function) . 查看https://socket.io/docs/client-api/上的文档,它指出它应该作为socket.on(event, callback function)
Are the parenthesis in the callback function always required for it to work? 是否始终需要在回调函数中使用括号才能使其正常工作? Because it seems like they are working elsewhere without parenthesis. 因为似乎他们在没有括号的情况下在其他地方工作。 Any resources or pointers to documentation is much appreciated. 非常感谢任何资源或指向文档的指针。

In order to call a function (callback or whatever), while the function does not get any arguments, you should still call it with () . 为了调用一个函数(回调或其他方法),尽管该函数没有任何参数,您仍应使用()调用。 IE: onsocketConnected () ; IE: onsocketConnected () ;

The reason socket.on('connect', onsocketConnected); 原因socket.on('connect', onsocketConnected); didn't work is because you are missing () while calling for a function. 没用是因为在调用函数时缺少()
What you are doing by this, is just passing the variable/object (which does not exist) onsocketConnected to socket.on method, instead of passing a Function. 您正在执行的操作只是将onsocketConnected上的变量/对象 (不存在) onsocketConnectedsocket.on方法,而不是传递Function。

The right way to use it, is just as you typed afterwards: socket.on('connect', onsocketConnected()); 正确的使用方式,就像您在之后键入的一样: socket.on('connect', onsocketConnected());

Documentation about JS function arguments: http://devdocs.io/javascript/functions/arguments 有关JS函数参数的文档: http : //devdocs.io/javascript/functions/arguments

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM