user7236363
user7236363

Reputation: 15

Typescript reference right this in callback

When I try to use the sendUserMessage() from Class 1 I get an error that content is undefined. I know that it has to do with the this but I am unable to find an answer that fits into my situation.

Class 1:

    @ViewChild(Content) content: Content;

    sendUserMessage(message) {
        this.class2object.sendMessageToBackend(message,this.createMessage);

    }


    createMessage(jsonMessage) {
        this.content.scrollToBottom(300);
    }

Class 2:

 sendMessageToBackend(ChatMessage: string, handler: Function) {
    //build requests
    var response: string;
    var time = new Date().getTime();
    var json = JSON.stringify({ message: ChatMessage, sessionID: "", timestamp: time });
    var headers = new Headers();
    headers.append("Content-Type", 'application/json');

    // send request
    this.http.post('http:somethhing.smth',
        json, {
            headers: headers
        }).subscribe(data => {
            response = JSON.parse(JSON.stringify(data.text()));
            handler(response);
        },
        () => console.log("error")
        );
}

Note: Methods here are simplified for better understanding.

I get the error EXCEPTION: Cannot read property 'content' of undefined

I know that one solution would be to move the method in Class 2 to Class 1 but I would really try to avoid this.

Upvotes: 0

Views: 258

Answers (2)

Paleo
Paleo

Reputation: 23772

Use an arrow function:

this.class2object.sendMessageToBackend(message, jsonMessage => this.createMessage(jsonMessage));

I suggest to read this article: Understanding "This" in JavaScript.

Notice: The closure (our small arrow function) has better performance than the bind function.

Upvotes: 1

Naveen Motwani - AIS
Naveen Motwani - AIS

Reputation: 619

Use bind function

 this.class2object.sendMessageToBackend(message, this.createMessage.bind(this));

Hope it help.

Upvotes: 0

Related Questions