I have an mvc application where I am writing the client side code in TypeScript, as well as using several well known javascript libraries, including knockout, amplifyjs, and requirejs. I have ran into a situation where the expected behavior isn't what happens.
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; });
});
}
}
}
The problem is in addSurvey(). Inside the amplify request, I expected the 'this' keyword to still point to the instance of the class. Instead, it pointed to the entire window. I had a workaround, which was to use knockout to go get the context from the DOM, but this really doesn't seem like it's a good idea.
Is there a better way of handling this using typescript?