【问题标题】:Can I use reserved key word "in" in CoffeeScript?我可以在 CoffeeScript 中使用保留关键字“in”吗?
【发布时间】:2013-03-15 19:27:29
【问题描述】:

我正在尝试将 coffeescriptsocket.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无法正确编译。

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

【问题讨论】:

  • 什么是编译错误信息?
  • 没有错误。但是coffeescript会将io.sockets.in("foobar")编译成io.sockets["in"]("foobar")
  • @OrionChang 没关系。这两个符号在 JavaScript 中是等价的。
  • 这实际上是一个咖啡功能

标签: node.js coffeescript socket.io


【解决方案1】:

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

我假设你在 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");

正如 cmets 中所述,以下两行在 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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多