1

我想向用户显示 socket.io 连接的状态。为此,我有一堆这些要告诉用户。

#I can't use `*` because I have some customized events
socket.on 'my_command', =>
    set_status "connecting"

socket.on 'connecting', =>
    set_status "connecting"

socket.on 'disconnect', =>
    set_status "disconnect"

socket.on 'connect_failed', =>
    set_status "connect_failed"

有没有办法将所有这些压缩成更小的东西?就像是:

socket.on 'connecting, disconnect, connect_failed', (name_of_event)=>
    set_status name_of_event
4

2 回答 2

1

似乎socket.io没有提供这样的短手绑定。你可以把它写在一个 for 循环中。

for event in ['connecting', 'disconnect', 'connect_failed']
  do (event) =>
    socket.on event, =>
      set_status event

# or
for event in 'connecting, disconnect, connect_failed'.split(/,\s*/)
  do (event) =>
    socket.on event, =>
      set_status event
于 2013-06-11T09:06:18.043 回答
0

从 Socket.IO v3 开始,引入了 Catch-all 监听器:

socket.onAny((eventName, ...args) => {
  // ...
});

您可以在侦听器中为不同的情况添加条件逻辑。

查看官方文档以获取更多信息:catch-all listeners

于 2022-02-09T21:12:50.007 回答