在socket.io中侦听多个事件

时间:2013-06-11 06:16:07

标签: javascript events javascript-events coffeescript socket.io

我想向用户显示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

1 个答案:

答案 0 :(得分: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