Установка переменной в асинхронном вызове JavaScript
У меня есть объект x
класса C
, Атрибут x.myval
должен быть установлен по телефону x.load()
, который в свою очередь должен получить свои данные от асинхронного вызова AJAX.
class C {
constructor() {
this.myval = "hello";
}
load() {
return $.ajax({
type: "GET",
url: "file.txt",
// suppress "xml not well-formed error in firefox",
beforeSend: function(xhr){
if (xhr.overrideMimeType) { xhr.overrideMimeType("text/plain"); }
},
contentType: "text/plain",
dataType: "text",
success: function(text) {
this.myval = text;
}
});
}
}
var x = new C();
$.when(x.load()).done(function(a1,a2) {
console.log(x.text); //should print the content of file.txt
});
Я получаю ошибку this.myval is undefined
очевидно, потому что this
установлен в this
JQuery-$
,
Я также попробовал:
class C {
constructor() {
this.myval = "hello";
}
load() {
var callback = function callbackClosure(mythis) {return function(text) {
this.myval = text;
}}(this);
return $.ajax({
type: "GET",
url: "file.txt",
// suppress "xml not well-formed error in firefox",
beforeSend: function(xhr){
if (xhr.overrideMimeType) { xhr.overrideMimeType("text/plain"); }
},
contentType: "text/plain",
dataType: "text",
success: callback
});
}
}
var x = new C();
$.when(x.load()).done(function(a1,a2) {
console.log(x.text); //should print the content of file.txt
});
Но это исключение jQuery.Deferred exception: assignment to undeclared variable...
1 ответ
Решение
this
не ссылается на ваш экземпляр в этой строке:
success: function(text) {
this.myval = text;
}
Вы можете создать временную переменную, ссылающуюся на ваш экземпляр во внешнем методе, например так:
load() {
var that = this;
return $.ajax({
type: "GET",
url: "file.txt",
// suppress "xml not well-formed error in firefox",
beforeSend: function(xhr){
if (xhr.overrideMimeType) { xhr.overrideMimeType("text/plain"); }
},
contentType: "text/plain",
dataType: "text",
success: function(text) {
that.myval = text;
}
});
}
Или вы можете использовать функцию стрелки:
load() {
return $.ajax({
type: "GET",
url: "file.txt",
// suppress "xml not well-formed error in firefox",
beforeSend: function(xhr){
if (xhr.overrideMimeType) { xhr.overrideMimeType("text/plain"); }
},
contentType: "text/plain",
dataType: "text",
success: (text) => {
this.myval = text;
}
});
}