2013-04-10 60 views
3

這是幾乎相同的所有其他this範圍問題我讀過目前爲止,除了一個微小的差異,這使得它相關(imo)問這個問題。問題與兒童範圍這在打字稿

現在本來我的問題與淘汰賽和打字稿範圍界定的this,所以給出如下:

class ViewModel 
{ 
    public SomeObservableArray = new ko.observableArray(); 

    public AddToTheObservableArray(someJsonData: any) 
    { 
     this.SomeObservableArray.push(new SomePojo(someJsonData)); 
    } 
} 

所以在上面的代碼中this位將炸燬因爲打字稿讓你認爲this是類例如,但實際上它是因爲Ajax回調或視圖元素的一些其他這一點,無論是覆蓋this關鍵字的情況。

所以要解決這個問題,大多數解決方案都是將該代碼移動到類的構造函數中,我個人覺得這很恐怖,但是考慮到使用TypeScript獲得的其他好處,這種少量的恐怖是可以接受的。所以只是讓大家都在同一頁上,下面的代碼解決了上述問題:

class ViewModel 
{ 
    public SomeObservableArray = new ko.observableArray(); 
    public AddToTheObservableArray = (someJsonData: any) => Void; 

    constructor 
    { 
     this.AddToTheObservableArray = (someJsonData: any) => { 
      this.SomeObservableArray.push(new SomePojo(someJsonData)); 
     }; 
    } 
} 

我只是寫這個例子的代碼了我的頭頂部,所以我對任何錯別字等道歉,但它hilights的共同面臨的問題以及常見的解決方案/解決方法。

NOW!我有問題,就是從這裏開始的下一步計劃,我有一些代碼,像這樣:

class ViewModel 
{ 
    public SomeObservableArray = new ko.observableArray(); 
    public AddToTheObservableArray = (someJsonData: any) => Void; 


    constructor 
    { 
     this.PopulateObservableArray = (someJsonArrayData: any) => { 
      this.SomeObservableArray.removeAll(); 
      someJsonArrayData.forEach(function(someJsonData) { 
       this.SomeObservableArray.push(new SomePojo(someJsonData)); 
      }); 
     }; 
    } 
} 

所輸出的代碼看起來像這樣:

var ViewModel = (function(){ 
    function ViewModel(){ 
     var _this = this; 

     this.SomeObservableArray = new ko.observableArray(); 

     this.AddMultipleEntitiesToObservableArray = function(someJsonArrayData) { 
      _this.SomeObservableArray.removeAll(); 
      someJsonArrayData.forEach(function(someJsonData) { 
       this.SomeObservableArray.push(new SomePojo(someJsonData)); 
      }); 
     } 
    }; 
    return ViewModel; 
})(); 

我再次對任何錯字道歉,因爲我只是簡化較大的項目輸出,但是在這裏看到的主要的事情是,在foreach方法孩子this仍然存在,所以我得到的錯誤this.SomeObservableArray is undefined

我確信1個可能的解決方案是提取出來的foreach並使其成爲自己的方法,然而,這感覺就像在blutack上粘貼細胞帶,所以我想知道是否有一些更優雅的解決方案或我的一些不當行爲這可以改變,至少不必讓它更難讀。

+0

我在TypeScript https:// www上做了關於this這個主題的視頻教程。 youtube.com/watch?v=tvocUcbCupA&hd=1 – basarat 2014-04-21 05:41:32

回答

6

是有,它實際上是很容易的。只需使用lambda表達式上任何方法你想獲得作用域更高的功能範圍。你的情況,你需要重寫你的例子如:

class ViewModel 
{ 
    public SomeObservableArray = new ko.observableArray(); 
    public AddToTheObservableArray = (someJsonData: any) => Void; 


    constructor() 
    { 
     this.PopulateObservableArray = (someJsonArrayData: any) => { 
      this.SomeObservableArray.removeAll(); 
      someJsonArrayData.forEach((someJsonData) => { 
       this.SomeObservableArray.push(new SomePojo(someJsonData)); 
      }); 
     }; 
    } 
} 

PS:它被認爲是最好的做法不是操縱在每個可觀察到的數組,數組的用戶將每項更改通知。只需將你的數據推送到一個臨時數組,然後將這個數組設置爲可觀察數組的值(我的2cts)。

+2

我與你的PS完全一致,只是使這個例子作爲起來我去。如果你的解決方案使目前的代碼更優雅,那麼你的先生是我的英雄! – Grofit 2013-04-10 12:39:58

+0

很高興能有幫助:) – thomaux 2013-04-10 12:41:01