SignalR类方法回调和'这个'

时间:2017-03-28 19:17:21

标签: javascript signalr es6-class

我有一个类似的问题,但不一样。这个关注于新的ES6类关键字以及如何处理它。 SignalR正在调用类方法。当进入那个类的方法时,这个'指的是SignalR集线器而不是类实例本身。如何在SignalR使用新的ES6类调用的类成员中获取类实例?

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();
        });
    }
}

1 个答案:

答案 0 :(得分:1)

使用类时,最好使用箭头功能,以便正确设置“此”。

在您的示例中,您将sayHello分配给客户端的hello方法。那时你需要将gameLoad绑定到它:

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

或者,您可以将sayHello转换为箭头函数:

sayHello = () => {
相关问题