0

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
  • 1
    Use an arrow function. `.done((response) => this.bar = response.bar});` – Ruan Mendes Oct 08 '21 at 14:30
  • 3
    Lets say that the AJAX call takes an hour to download. How are you going to handle that? (tip: you must handle async calls) – Rickard Elimää Oct 08 '21 at 14:31
  • 1
    The `this` in your `done()` method does not refer to the class. – Terry Oct 08 '21 at 14:32
  • Worth a quick search for [JS what is this](https://www.google.com/search?q=js+what+is+this) – jarmod Oct 08 '21 at 14:33
  • Also, [How to access the correct this inside a callback](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Heretic Monkey Oct 08 '21 at 14:34
  • *"so I don't think the issue is me logging before the ajax call completes."* No that's exactly one of the two issues. See the duplicates. "Late binding" has nothing to do with this and `bax_unbound.bind(Foo);` can't work because `bax_unbound` is not a function. – Felix Kling Oct 08 '21 at 14:36
  • 2
    Doing work like sending AJAX from a constructor is usually considered an anti-pattern. You should have a method to so you can decide when to make the AJAX call. See http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/ This is along the same lines as what @RickardElimää mentioned. A method to send the AJAX could return a promise so you can get its value when it's ready. – Ruan Mendes Oct 08 '21 at 14:37

0 Answers0