我可以在CoffeeScript中使用保留的关键字“in”吗?

时间:2013-03-15 09:24:21

标签: node.js coffeescript socket.io

我正在尝试将 coffeescript socket.io 一起使用。

io = socketio.listen(server);
// handle incoming connections from clients
io.sockets.on('connection', function(socket) {
    // once a client has connected, we expect to get a ping from them saying what room they want to join
    socket.on('room', function(room) {
        socket.join(room);
    });
});

// now, it's easy to send a message to just the clients in a given room
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party people?');

// this message will NOT go to the client defined above
io.sockets.in('foobar').emit('message', 'anyone in this room yet?'); 

io.sockets.in 无法正确编译。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

在您的问题中,您声明存在编译器错误,但在评论中您说没有。如果有,你真的应该发布你的coffeescript代码:)

我假设你在coffeescript中有这样的东西:

io = socketio.listen server

io.sockets.on 'connection', ->
    socket.on 'room', ->
        socket.join room

room = "abc123"
io.sockets.in(room).emit "message", "foobar"

io.sockets.in("foobar").emit "message", "barbaz"

编译为

io = socketio.listen(server);

io.sockets.on('connection', function() {
  return socket.on('room', function() {
    return socket.join(room);
  });
});

room = "abc123";

io.sockets["in"](room).emit("message", "foobar");

io.sockets["in"]("foobar").emit("message", "barbaz");

正如评论中所述,以下两行在JavaScript中是等效的:

io.sockets["in"](room).emit("message", "foobar");
io.sockets.in(room).emit("message", "foobar); 

您可以通过打开自己喜欢的JavaScript控制台来验证这一点:

> var test = { foo: "bar" }
> test.foo
'bar'
> test["foo"]
'bar'