2013-04-04 122 views
2

我正在嘗試使用typescript,Knockout和azure移動服務來獲取一些數據。問題是當我從azure獲取數據時,它是異步的,我無法再獲取viewmodel對象。我認爲這是一些範圍/關閉問題,請幫我找到解決方案。它在Done()的回調函數中爲null;JavaScript和TypeScript範圍問題

這裏是我的打字稿代碼:

class pmViewModel { 
    public welcomeMsg: string; 
    public totalCount: number; 
    constructor() { 
     this.welcomeMsg = ""; 
    } 
} 

class Manager { 
    client: any; 
    portalVM: pmViewModel; 
    constructor() { 
     this.client = new WindowsAzure.MobileServiceClient("url", "key"); 
     this.portalVM = new pmViewModel(); 
    } 

    LoadData() { 
     console.log("load data for management portal"); 
     this.portalVM.welcomeMsg = "Hello"; 
     this.portalVM.totalCount = 0; 
     var dataTable = this.client.getTable('dataTable'); 

     dataTable.take(1).includeTotalCount().read().done(this.populateTotal,this.portalVM); 

     ko.applyBindings(this.portalVM); 
     }; 

     populateTotal(result, vm) { 
      console.log(result); 
      console.log(vm); //null here 
      this.portalVM.totalCount = 100000;////this is also null 
     } 
} 

和生成的JavaScript代碼:

var pmViewModel = (function() { 
    function pmViewModel() { 
     this.welcomeMsg = ""; 
    } 
    return pmViewModel; 
})(); 
var Manager = (function() { 
    function Manager() { 
     this.client = new WindowsAzure.MobileServiceClient("url", "key"); 
     this.portalVM = new pmViewModel(); 
    } 
    Manager.prototype.LoadData = function() { 
     console.log("load data for management portal"); 
     this.portalVM.welcomeMsg = "Hello"; 
     this.portalVM.totalCount = 0; 
     var dataTable = this.client.getTable('dataTable'); 
     dataTable.take(1).includeTotalCount().read().done(this.populateTotal, this.portalVM); 
     ko.applyBindings(this.portalVM); 
    }; 
    Manager.prototype.populateTotal = function (result, vm) { 
     console.log(result); 
     console.log(vm); 
     this.portalVM.totalCount = 100000; 
    }; 
    return Manager; 
})(); 
+0

你需要顯示在錯誤發生。 – RobG 2013-04-04 02:56:30

+0

在完成方法回調(我在那裏寫了一些評論) – 2013-04-04 02:59:55

回答

2

相關線路的位置:

dataTable.take(1).includeTotalCount().read().done(this.populateTotal,this.portalVM); 

您需要捕獲的 '這個' 結合因爲它將在沒有上下文的情況下作爲回調被調用。

選項1:

[etc...].done((result, vm) => this.populateTotal(result, vm), this.portalVM); 

選項2:

[etc...].done(this.populateTotal.bind(this), this.portalVM); 
+0

您的解決方案看起來是正確的,但所有函數都有自己的上下文。問題在於* LoadData *的'this'值未設置爲OP所期望的對象。 「this」的值由調用設置,這就是你所做的。 – RobG 2013-04-04 04:56:26

+0

謝謝,今晚我會試試 – 2013-04-04 17:10:51

+0

謝謝,它工作。我做了些微修改。 (結果)=> this.populateTotal(result),this.portalVm) populateTotal(result){ this.portalVm.totalCount = result.totalCount; ko.applyBindings(this.portalVm); } – 2013-04-04 23:03:01