2013-04-01 40 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

哦。這就是我正在使用我的代碼,我還沒有發現問題。你可以給我一個頭。 –