DEV Community

Discussion on: New to node.js and struggling with socket.io

Collapse
 
peerreynders profile image
peerreynders • Edited

socket.on(eventName, listener)
Socket#id
How does that work?

Watch for the casing on the variable names:

// 1. "socket" all lowercase
const socket = io("ws://localhost:3000");

// 2. "socket" all lowercase
socket.on("connect", () => {
  // 3. "socket" all lowercase
  console.log(socket.id);
});
Enter fullscreen mode Exit fullscreen mode

Basically the listener is a function expression (arrow functions are always function expressions) - and a function has access to all the variables in the scope that created it (in this case socket).

MDN: Closures

A function declaration

const socket = io("ws://localhost:3000");

socket.on("connect", connectListener);

// function declaration...
function connectListener() {
  // ...also has access to the enclosing scope
  console.log(socket.id);
}
Enter fullscreen mode Exit fullscreen mode

would work as well.

Collapse
 
fletch0132 profile image
Fletcher Moore

Thank you. I think it was just my phone adding the caps but I'll double check my code. Thank you