I have an object x
of class C
. The attribute x.myval
should be set by calling x.load()
, which in turn should get its data from an asynchronous ajax call.
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
});
I get an error this.myval is undefined
, obviously because this
is set to this
of jquery-$
.
I also tried:
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
});
But this trew an exception jQuery.Deferred exception: assignment to undeclared variable...