2

Recently, I've come across this problem where I had two methods in a class. One was referring to another but the other wasn't being recognized even though I could execute them individually.

class ButtonProcessor {
    buttonClick() {
        this.otherMethod();
    }

    otherMethod() {
        console.log("This does not work!");
    }
}

var buttonProcessor = ButtonProcessor;

document.getElementById("button").onclick = buttonProcessor.buttonClick;

The first method was called from a button click which was associated with a callback to that method.

Demomaker
  • 118
  • 1
  • 7

1 Answers1

0

One solution I found for this is to make the method that is called by the button a seperate function from the class and make it reference a class object that was already being used else-where. This is because apparently, when a method is referenced in a callback, using this to refer to another method doesn't work, because the callback only considers that one method.

class ButtonProcessor {

    otherMethod() {
        console.log("This does work!");
    }
}

var buttonProcessor = ButtonProcessor;

function buttonClick() {
    buttonProcessor.otherMethod();
}

document.getElementById("button").onclick = buttonProcessor.buttonClick;

Could there be another way to fix this?

Demomaker
  • 118
  • 1
  • 7
  • 1
    This is one of the most often-duplicated questions on the site. It doesn't need to be answered, it's already thoroughly answered [here](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback). – T.J. Crowder May 13 '20 at 15:21
  • 1
    @T.J.Crowder one thing though, is that these other questions are hard to find. – Demomaker May 13 '20 at 15:22
  • 1
    All due respect, this one isn't. – T.J. Crowder May 13 '20 at 15:30
  • 1
    I mean, not everyone knows that the problem is the "this" in the callback, so they probably won't search for that and won't find that question and that answer. – Demomaker May 13 '20 at 15:34