TeraNova
TeraNova

Reputation: 45

Variable is always undefined when called in a function

Before I come to my question, here is my Typescript class:

export class Info {

    private currentId: number;

    private addToListButton: HTMLInputElement;

    constructor() {
        this.currentId = +(<HTMLInputElement> document.getElementById("Example")).value;

        this.addToListButton = <HTMLInputElement> document.getElementById("addToList");

        this.registerEvents();
    }

    private registerEvents(): void {
        this.addToListButton.addEventListener("click", (() => this.addToList()));
    }

    private addToList(): void {
        var data: SomeModel;
        data.id = this.currentId;

        // ajax stuff
    }
}

My problem is when I want to get the "currentId" for the model, it's always undefined. The other variable "addToListButton" can I use in the same function without problems.

I can't see what's the problem there.

Thanks for your help!

Upvotes: 1

Views: 67

Answers (2)

Baboo
Baboo

Reputation: 4258

The keyword this in the function addToList doesn't refer to the instance of the class Info when the function is called here this.addToListButton.addEventListener("click", (() => this.addToList()));.

To have this refering to the instance, use an arrow function:

private const addToList = (): void => { // Arrow function
  var data: SomeModel;
  data.id = this.currentId;

  // ajax stuff
}

Here are some explanations on what arrow functions are.

Upvotes: 2

Randy Casburn
Randy Casburn

Reputation: 14165

In the addToList() method, the keyword this refers to the event context not the Info object context.

To use in this manner, you'll need to bind the method to the class. Add this to the constructor:

this.addToList = this.addToList.bind(this);

Upvotes: 0

Related Questions