【发布时间】: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 中获取上下文,但这似乎不是一个好主意。
有没有更好的使用打字稿处理这个问题的方法?
【问题讨论】:
-
在 TypeScript 中更好地理解
this:youtube.com/watch?v=tvocUcbCupA&hd=1
标签: knockout.js this typescript amplifyjs