I'm writing a JavaScript class for an object that will get data via ajax on creation. The object and its retrieved data will then be available for use later on.
The problem is that the variables don't update with new values from the ajax call. They stay at whatever values they were initiated at.
Here's a simplified example of my code:
class Foo {
constructor() {
this.bar = 0;
this.makeAjaxCall();
}
makeAjaxCall() {
jQuery.get(
// ajax logic
)
.done(
function(response) {
this.bar = response.bar;
}
);
}
}
var bax = new Foo();
console.log(bax.bar); // outputs 0
I've confirmed that the ajax call occurs, both via the network monitor and by console logging the response variable. It's just that the change of variable value doesn't "stick". This also occurs with code later on, so I don't think the issue is me logging before the ajax call completes.
I suspect this is related to late bindings in JavaScript, but I haven't been able to wrap my head around that. Here's what I tried in that realm (it didn't work):
var bax_unbound = new Foo();
var bax = bax_unbound.bind(Foo);
console.log(bax.bar); // still outputs 0