Kyle
Kyle

Reputation: 33691

How do I access a class function from inside a event in the contructor?

I am adding a change event to an ID in my class constructor in typescript, and inside that change event I would like to access a class function, but 'this' seems to not be the class when inside the event. How do I access the function from there?

export class Document_Uploads {

        constructor() {
            $("#FormBrokerReferenceID").change(function () {
                 = $("#FormBrokerReferenceID").val();

                //inside this event it does not work           
                this.Validate()

            });

             // works here inside constructor
            this.Validate()

        }

    Validate() {
            var valid: bool = true;
             some other code
    }


}

Upvotes: 0

Views: 1003

Answers (1)

Fenton
Fenton

Reputation: 250922

There are two solutions to your problem.

The first is to get TypeScript to handle the scope for you:

    constructor() {
        $("#FormBrokerReferenceID").change( () => {
             = $("#FormBrokerReferenceID").val();

            // Should now work...         
            this.Validate()

        });

         // works here inside constructor
        this.Validate()
    }

The second is to handle it yourself, although this is manually doing what TypeScript would do for you - it is worth knowing that it isn't magic. This can be useful if you don't want to overwrite the meaning of this in the event, but want access to the "outer" this too.

    constructor() {
        var self = this;

        $("#FormBrokerReferenceID").change(function () {
             = $("#FormBrokerReferenceID").val();

            // Should now work...         
            self.Validate()

        });

         // works here inside constructor
        this.Validate()
    }

Upvotes: 5

Related Questions