我有一個mvc應用程序,我在TypeScript中編寫客戶端代碼,以及使用幾個衆所周知的JavaScript庫,包括knockout,amplifyjs和requirejs 。我遇到了預期的行爲不會發生的情況。「this」關鍵字當混合Typescript,Knockout,Amplify和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'關鍵字仍然指向類的實例。相反,它指向整個窗口。我有一個解決方法,即使用knockout從DOM獲取上下文,但這看起來並不是一個好主意。
有沒有更好的方式來處理這個使用打字稿?
要了解'this'一點在打字稿更好:https://www.youtube.com/watch? v = tvocUcbCupA&hd = 1 – basarat