【问题标题】:"this" keyword when mixing Typescript, Knockout, Amplify, and RequireJs混合 Typescript、Knockout、Amplify 和 RequireJs 时的“this”关键字
【发布时间】:2013-03-22 16:19:26
【问题描述】:

我有一个 mvc 应用程序,我在其中使用 TypeScript 编写客户端代码,并使用了几个知名的 javascript 库,包括 knockout、amplifyjs 和 requirejs。我遇到了一种情况,即预期的行为不是发生的。

export class OrganizationOverviewViewModel{

    openedAssessments = ko.observableArray();
    availableSurveys = ko.observableArray();

    organizationAgentId = ko.observable();
    organizationName = ko.observable();

    selectedSurvey = ko.observable();

    public addSurvey() {
        if (this.selectedSurvey() === undefined) {
            mh.MessageHub.showError("Please Select a Survey", "what");
        }
        else {
            // we can do the post.
            // get the selected survey
            var surveyId = this.selectedSurvey();
            // call the server to add the survey

            amplify.request("addSurveyToOrganization", {
                "surveyId": surveyId,
                "organizationAgentId": this.organizationAgentId()
            },
            function (data) {
                var context = ko.contextFor($('#mainContent')[0]).$data;
                context.openedAssessments.push({ surveyId: data.SurveyId, SurveyName: data.SurveyName, NumberOfResponses: data.ResponseCount });
                context.availableSurveys.remove(function (item) { return item.SurveyId == surveyId; });
            });
        }
    }

}

问题出在 addSurvey() 中。在放大请求中,我希望“this”关键字仍指向该类的实例。相反,它指向整个窗口。我有一个解决方法,即使用敲除从 DOM 中获取上下文,但这似乎不是一个好主意。

有没有更好的使用打字稿处理这个问题的方法?

【问题讨论】:

标签: knockout.js this typescript amplifyjs


【解决方案1】:

在 Typescript 中,“this”关键字遵循 javascript 语义,而不是像 C# 这样的 OO 语言的语义......(现在?)

“this”正确指向对象的唯一地方是通过构造函数。所以你需要这样写:

export class OrganizationOverviewViewModel{

    public addSurvey;

    constructor() {
        this.addSurvey = () => {
           // you can safely use 'this' in here
           ...
        }
    }
    :
}

编辑:新版本 (0.9.1) 允许您将“this”用于 lambda 字段初始值设定项(NOT 函数)。所以你可以使用下面的代码来转换上面的代码。

export class OrganizationOverviewViewModel{

    public addSurvey = () => {
        // you can safely use 'this' in a field initializer
    }

    public badSurvey_dont_use_this() {
        // 'this' is probably not the 'this' you're looking for
    }
}

【讨论】:

  • 是否将self=this; 添加到每个方法的开头。然后把 self 当作对象工作的引用?
  • 哦。这就是我对我的代码所做的,我还没有发现问题。你能给我提个醒吗?
  • self=this 现在为我工作 - 第一天使用 TS 版本 1.0。所谓作品,我的意思是编译时没有波浪线。这是一个新的“功能”吗?
【解决方案2】:

看看TypeScript and Knockout binding to 'this' issue - lambda function needed? - 与雷提到的方法相同,这似乎是正确的

【讨论】:

    猜你喜欢
    • 2017-12-31
    • 1970-01-01
    • 2011-10-19
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    相关资源
    最近更新 更多