Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Can I use reserved key word "in" in CoffeeScript?

Can I use reserved key word "in" in CoffeeScript?

Problem

I'm trying to use coffeescript with 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 can not be compiled correctly.

How should I solve this problem?

Problem courtesy of: Orion Chang

Solution

In your question you state that there is a compiler error, but in the comments you say that there isn't. If there is, you really should post your Coffeescript code as well :)

I'm assuming that you've got something like this in 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"

Which compiles to

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");

As it has been stated in the comments, the following two lines are equivalent in JavaScript:

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

You can verify this by opening up your favorite JavaScript console:

> var test = { foo: "bar" }
> test.foo
'bar'
> test["foo"]
'bar'
Solution courtesy of: fresskoma

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Can I use reserved key word "in" in CoffeeScript?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×