2013-04-01 38 views
1

我有一个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获取上下文,但这看起来并不是一个好主意。

有没有更好的方式来处理这个使用打字稿?

+0

要了解'this'一点在打字稿更好:https://www.youtube.com/watch? v = tvocUcbCupA&hd = 1 – basarat

回答

5

在打字稿中“this”关键字如下JavaScript的语义,而不是面向对象的语言,如C#的语义...(现在?)

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

export class OrganizationOverviewViewModel{ 

    public addSurvey; 

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

编辑:新版本(0.9.1),您可以使用“本”为拉姆达字段初始化(不是函数)。因此,您可以使用以下代码转换为上面的代码。

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 
    } 
} 
+0

是否添加'self = this;'开始每种方法。然后将自我视为对象工作的参照? –

+0

不要试一试。 – Ray

+0

哦。这就是我正在使用我的代码,我还没有发现问题。你可以给我一个头。 –