1

I'm using the Definitely Typed typescript definition file for socketio, but I am having scope issues when trying to bind events.

module testScope {
    import Socket = SocketIOClient.Socket;
    export class testClass {
        socket: Socket;
        constructor(){
            this.socket = io.connect();
            this.socket.on('test', this.testCallback);
        }
        testCallback(){
            console.log(this);
        }
    }
}

The console.log call outputs a Socket object instead of a testClass object. Any way I can fix this? If possible, without adding another layer of events system.

Doing it this way is also a no go, has "this" has no method testCallback:

module testScope {
    import Socket = SocketIOClient.Socket;
    export class testClass {
        socket: Socket;
        constructor(){
            this.socket = io.connect();
            this.socket.on('test', function(){ this.testCallback(); });
        }
        testCallback(){
            console.log(this);
        }
    }
}
PierrePaul
  • 383
  • 1
  • 9

1 Answers1

1

Even if you are using classes the scoping rules for this in class methods are still the same as the ones in javascript functions (methods end up as functions after they are transpiled).

Instead use the arrow function to maintain the same lexical scope.

module testScope {
    import Socket = SocketIOClient.Socket;
    export class testClass {
        socket: Socket;
        constructor(){
            this.socket = io.connect();
            this.socket.on('test', () => this.testCallback()); // this is now testClass
        }
        testCallback(){
            console.log(this);
        }
    }
}

You can find more on how this works here.

You can find more on the arrow functions here.

Community
  • 1
  • 1
toskv
  • 30,680
  • 7
  • 72
  • 74