Ajax调用后无法更新类变量

时间:2019-06-06 12:01:30

标签: javascript jquery ajax class

在完成ajax请求后获得两个整数之后,this.N不会设置this.MstoreDims(),即使dims已被正确解码。因此,似乎无法访问构造函数中声明的this.Nthis.M。 这是代码

class MapModel {

    constructor() {
        this.N; // need to initialize this after an ajax call
        this.M;
        this.seats = new Array();
        this.remote_seats = new Array();
    }

    init(callback) {
        let _this = this;
        $.when(
            _this.getDims(),
            _this.getSeats(),
        ).then(this.initMap(callback))
    }


    initMap(callback) {
        console.log(this.N); // prints undefined
        console.log(this.M); // this as well
        callback(this.N, this.M, this.seats);
    }

    getDims() {
        let _this = this;
        $.ajax({
            url: 'src/php/data.php',
            type: 'POST',
            data: {action: 'getDims'},
            success: function (result) {
                let dims = JSON.parse(result); // dims[0] = 10, dims[1] = 6
                _this.storeDims(dims);
            }
        });
    }

    storeDims(dims) {
        console.log(dims);
        this.N = parseInt(dims[0]);
        this.M = parseInt(dims[1]);
        console.log(this.N);
        console.log(this.M);
    }

    getSeats() {
    let _this = this;
    $.ajax({
        url: 'src/php/data.php',
        type: 'POST',
        data: {action: 'getSeats'},
        success: function (result) {
            let seats = JSON.parse(result);
            _this.storeSeats(seats);
        }
    });
}

storeSeats(seats) {
    this.remote_seats = seats;
    console.log(this.remote_seats);
}
}

2 个答案:

答案 0 :(得分:0)

您需要从getDmsgetSeats函数返回ajax诺言

 getDims() {
        let _this = this;
        return $.ajax({
            url: 'src/php/data.php',
            type: 'POST',
            data: {action: 'getDims'},
            success: function (result) {
                let dims = JSON.parse(result); // dims[0] = 10, dims[1] = 6
                _this.storeDims(dims);
            }
        });
    }

您甚至可以将值直接传递给initMap

init(callback) {
        let _this = this;
        $.when(
          _this.getDims(),
          _this.getSeats()
        ).then(function(dims,seats) {_this.initMap(dims,seats,callback)})
    }


    initMap(dimsRaw,seatsRaw, callback) {
        let dims = JSON.parse(dimsRaw);
        console.log(dims[0]); 
        console.log(dims[1]); 
        callback(dims[0], dims[1], this.seats);
    }

答案 1 :(得分:0)

在链声明中正在调用init Promise回调,请尝试添加函数包装器:

    init(callback) {
        let _this = this;
        $.when(
            _this.getDims(),
        ).then(function() {_this.initMap(callback)})
    }