Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected typescript this is undefined type

Tags:

typescript

    /// <reference path="../typings/signalr/signalr.d.ts" />
/// <reference path="../typings/jquery/jquery.d.ts" />

interface IMyBlackjack {

}

module My {
    export class MyBlackjack implements IMyBlackjack {

        private hub: HubProxy;
        private cnn: HubConnection;

        constructor() {
            $("#formBlackJack").hide();

            this.cnn = $.hubConnection();
            this.hub = this.cnn.createHubProxy("blackjackHub");
            this.cnn.start(() => this.onConnStart);
        }

        private onConnStart(): void {
            $("#formBlackJack").show();
            this.hub.invoke('hello');
        }
    }
}

var myBlackjack: IMyBlackjack = new My.MyBlackjack();

there is a problem in the code:

this.hub.invoke('hello');

this.hub is surprisingly undefined.

And I hope it should be an object. Any thoughts about it ?

like image 922
alerya Avatar asked Feb 08 '15 19:02

alerya


1 Answers

this is not pointing to the instance. Fix use a lambda:

    private onConnStart = () => {
        $("#formBlackJack").show();
        this.hub.invoke('hello');
    }

More: https://www.youtube.com/watch?v=tvocUcbCupA

also

this.cnn.start(() => this.onConnStart);

perhaps you meant to call i.e. () => this.onConnStart()

like image 78
basarat Avatar answered Oct 23 '22 10:10

basarat