okurelin
okurelin

Reputation: 11

Define socket io function outside of "on" statement

I'm writing code with Socket.io in JavaScript and I've been trying to define the function that happens during a certain event outside of the event statement because I want to reuse the function later. So instead of the usual:

socket.on('eventName',function(input){
   //code triggered by event
});

I want to declare the function beforehand and then use it in the "on" statement:

function myFunction(input){
  //some code
}
socket.on('input', myFunction(input));

So far I haven't had any success and I keep getting this error in Terminal:

nodejs exception: ReferenceError: input is not defined

in reference to the input being sent from the client with the 'input' event. Do I always have to define the code that happens when the event is triggered in the "on" statement?

Upvotes: 0

Views: 66

Answers (1)

robertklep
robertklep

Reputation: 203304

What you want is to pass a reference to myFunction, like this:

socket.on('input', myFunction);

What you're doing with myFunction(input) is actually executing myFunction with an undefined variable input as its argument (hence the error).

Upvotes: 1

Related Questions