0

I had a similar question but not the same. This one focuses on the new ES6 class keyword and how to handle this. SignalR is calling a class method. When inside that class method 'this' refers to the SignalR hub not the class instance itself. How can I get the class instance inside this class member that SignalR called using the new ES6 classes?

class gameLoad {
    constructor(){

    }

    init(){
        // create the network object and hook it's functions update for loading
        this.network = $.connection.testHub;
        this.network.client.hello = this.sayHello;
    }

    // this is called from signalR and 'this' now refers to the signalR hub inside this function. how can I get the class instance?
    sayHello(){
        console.log(this);    // 'this' refers to signalR object not gameLoad object
    }

    create(){
        var self = this;
        $.connection.hub.start().done(function () {
            console.log("Started!")
            console.log("Calling server function.");

            // make our first network call which will turn around and call client.hello which is bound to this classes sayHello() member function
            self.network.server.hello();
        });
    }
}
user441521
  • 6,942
  • 23
  • 88
  • 160

1 Answers1

1

When using classes, it's best to use arrow functions so that you have 'this' properly set.

In your example, you assign sayHello to client's hello method. You will need to bind gameLoad to it at that time:

this.network.client.hello = this.sayHello.bind(gameLoad);

Alternatively, you can convert sayHello into an arrow function:

sayHello = () => {
Rob Brander
  • 3,702
  • 1
  • 20
  • 33
  • OK so calling bind() will make 'this' available inside that function then? I'm not a huge fan of the arrow function syntax but I'll give these a go. – user441521 Mar 29 '17 at 01:07