如何从构造函数中的事件内部访问类函数?

时间:2013-03-06 19:25:28

标签: typescript

我在我的类构造函数中的typescript中向一个ID添加了一个更改事件,并且在该更改事件中我想访问一个类函数,但是'this'似乎不是在事件内部的类。如何从那里访问该功能?

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
    }


}

1 个答案:

答案 0 :(得分:5)

您的问题有两种解决方案。

第一种是让TypeScript为您处理范围:

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

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

        });

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

第二种是自己处理它,虽然这是手动完成TypeScript会为你做的事情 - 值得知道它不是魔术。如果您不想在事件中覆盖this的含义,但想要访问“外部”,这可能很有用。

    constructor() {
        var self = this;

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

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

        });

         // works here inside constructor
        this.Validate()
    }
相关问题