Reputation: 13399
I am trying to use typescript, Knockout and azure mobile services to get some data. The problem is when I get data from azure, it's async and I can not get the viewmodel object any more. I think it's some scope/closure issue, please help me find the solution. It is null in the call back function for Done();
Here is my TypeScript code:
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
}
}
and generated JavaScript code:
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;
})();
Upvotes: 3
Views: 354
Reputation: 220944
Relevant line here:
dataTable.take(1).includeTotalCount().read().done(this.populateTotal,this.portalVM);
You need to capture the 'this' binding of populateTotal
since it's going to be invoked as a callback without context.
Option 1:
[etc...].done((result, vm) => this.populateTotal(result, vm), this.portalVM);
Option 2:
[etc...].done(this.populateTotal.bind(this), this.portalVM);
Upvotes: 2