0

I have trouble in refactoring the following code block into separate functions.

socketHandler = (io) => {
  io.on('connection', (socket) => {
    socket.on('doLogin', data => {
      userService.getUserByName(data.uname)
        .then((doc) =>{
          if(doc && doc.pwd===data.pwd){
            socket.emit('onLogin', {status:'SUCCESS'});
          }
        }, (error) => {
          socket.emit('onLogin', {status:'Error in the application'});
        });
    });
  });
}

app.configure(socketio(socketHandler));

I tried refactoring the above code as follows.

doLogin = data => {
  userService.getUserByName(data.uname)
    .then((doc) =>{
      if(doc && doc.pwd===data.pwd){
        socket.emit('onLogin', {status:'SUCCESS'});
      }
    }, (error) => {
      socket.emit('onLogin', {status:'Error in the application'});
    });
}

socketHandler = (io) => {
  io.on('connection', (socket) => {
    socket.on('doLogin', doLogin);
  });
}

app.configure(socketio(socketHandler));

I am getting a run-time error as socket is not defined.

How to get reference to 'socket' in the function 'doLogin'?

I also tried the following way and could not make it work.

doLogin = socket => data => {

Also tried as follows

socket.on('doLogin', doLogin.bind(socket));

Need some help in fixing this.

Thanks.

2 Answers 2

2

After you broke up the functions you lost reference to socket object. You could try, in SocketHandler

socket.on('doLogin', (data) => doLogin(data, socket));

and redefine doLogin as

doLogin = (data, socket) => {
Sign up to request clarification or add additional context in comments.

Comments

0

doLogin.bind(socket) won't work if doLogin is arrow function, because arrow functions cannot be bound. Instead, it should be a regular function:

function doLogin(data) {
  const socket = this;
  ...
}
...
socket.on('doLogin', doLogin.bind(socket));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.