Tc_
Tc_

Reputation: 555

How to retain 'this' in a callback method?

I don't get how I'm supposed to get the reference of the app instance in the callback method. I've been looking at this: How to access the correct this inside a callback? but didn't really feel that I got something from it.

class App
{
  constructor()
  {
    this.imageHandler = new ImageHandler();
    this.imageHandler.loadImages(["img.jpg"], this.create);
  }

  create()
  {
    console.log("Here 'this' is undefined");
    console.log(this.imageHandler.images[0]);
  }
}

class ImageHandler
{
  constructor()
  {
    this.images = [];
  }

  loadImages(urls, callback)
  {
    urls.forEach((url) => {
      var img = new Image();
      this.images.push(img);
      img.onload = () => {
        if (this.images.length == urls.length) {
          callback();
        }
      }
      img.src = url;
    });
  }
}

So the clunky way could be chaining a reference to the original instance like this:

this.imageHandler.loadImages(["img.jpg"], this.create, this);

loadImages(urls, callback, self)

callback(self);

create(self)

console.log(self.imageHandler.images[0]);

But it seems like a really awkward way of doing it. Can I achieve it in another more elegant way?

Upvotes: 1

Views: 56

Answers (1)

Brad
Brad

Reputation: 163548

Instead of this:

this.imageHandler.loadImages(["img.jpg"], this.create);

Try this:

this.imageHandler.loadImages(["img.jpg"], this.create.bind(this));

The issue is that you're passing a reference to the method on the class, but it isn't bound to the instance in this unless you call .bind().

Upvotes: 4

Related Questions