【问题标题】:In Typescript how do I call a class method from another method in the same class that is called as an event handler在 Typescript 中,我如何从同一个类中的另一个方法调用一个类方法,该方法被称为事件处理程序
【发布时间】:2017-04-15 19:12:50
【问题描述】:

我有以下 TypeScript 代码:

class MyClass {
    constructor() {
         $("#MyButton").on("click", this.MyCallback);
         this.MyMethod();        
    }

    MyCallback = () => {
        $.ajax("http://MyAjaxUrl")
        .done(function() {                
            this.MyMethod();
        });
    }

    MyMethod = () => {
        // Do some work
    }    
}

我遇到的问题是,当它到达 JQuery ajax done 函数时,它告诉我“MyMethod 不是函数”。调试了 Javascript 我知道这是因为“this”不是对 MyClass 的引用,但我无法弄清楚在执行时如何获取对类的引用。

【问题讨论】:

标签: jquery ajax class events typescript


【解决方案1】:

能不能把代码改成:

$.ajax("http://MyAjaxUrl")
.done(() => {
    this.MyMethod();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2014-11-07
    • 2013-10-08
    相关资源
    最近更新 更多