我有一个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