在完成ajax请求后获得两个整数之后,this.N
不会设置this.M
和storeDims()
,即使dims
已被正确解码。因此,似乎无法访问构造函数中声明的this.N
和this.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);
}
}
答案 0 :(得分:0)
您需要从getDms
和getSeats
函数返回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)})
}