简体   繁体   中英

JavaScript and TypeScript scope issue

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;
})();

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM