3

我正在尝试使用 typescript、Knockout 和 azure 移动服务来获取一些数据。问题是当我从 azure 获取数据时,它是异步的,我无法再获取 viewmodel 对象。我认为这是一些范围/关闭问题,请帮我找到解决方案。在 Done() 的回调函数中为空;

这是我的打字稿代码:

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

1 回答 1

2

这里的相关行:

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

您需要捕获 'this' 绑定,populateTotal因为它将在没有上下文的情况下作为回调调用。

选项1:

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

选项 2:

[etc...].done(this.populateTotal.bind(this), this.portalVM);
于 2013-04-04T04:40:58.407 回答