2013-03-15 68 views
0

我正在尝试使用coffeescriptsocket.io可以在CoffeeScript中使用保留关键字“in”吗?

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不能正确编译。

我应该如何解决这个问题?

+0

什么是编译错误消息? – 2013-03-15 09:26:32

+0

没有错误。但是coffeescript会将** io.sockets.in(“foobar”)**编译为** io.sockets [“in”](“foobar”)**。 – 2013-03-15 09:29:44

+2

@OrionChang很好。这两个符号在JavaScript中是等效的。 – freakish 2013-03-15 09:40:51

回答

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'