JS – Calling class methods inside of callback function

I’m currently having a problem and don’t know how to solve it correctly.

I’m developing a web application with js using the WebMidi API.

I want to load all midi devices into a dropdown after WebMidi is loaded.
As far as I understood it I have to pass the enable function of Webmidi a callback function:

WebMidi.enable(function (err) {
  if (err) {
    console.log("WebMidi could not be enabled.", err);
  } else {
    console.log("WebMidi enabled!");
  }
});

The problem I am having is I cannot reference class methods inside
the callback function, but I have to call the method that’s fills the dropdown list with all midi inputs, as soon as WebMidi is enabled.

My code looks like this:

class MidiListener{
    constructor(){
        this.enable();
        this.fillDropdown(Webmidi.inputs);
    }
    enabledTest(err){
        if(err){console.log("F")}
        else{console.log("Yeeee")}
    }

    enable(){
        WebMidi.enable(function (err) {
            //Enable WebMidi
            if (err) {
              console.log("WebMidi could not be enabled.", err);
              window.alert("WebMidi is not supported by your Browser.")
            } 
            else {
                console.log("WebMidi enabled!");
            } 
        });
    }
...

The problem is fillDropdown() is called before WebMidi finished activating, and the array is empty at the time. Can I somehow reference class methods inside the callback function?

126 thoughts on “JS – Calling class methods inside of callback function”

  1. It’s a shame you don’t have a donate button! I’d most certainly donate to this brilliant
    blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account.
    I look forward to fresh updates and will share
    this website with my Facebook group. Chat soon!

    Reply
  2. Great work! This is the kind of info that are meant to be shared across the
    internet. Shame on Google for no longer positioning this post higher!
    Come on over and talk over with my website . Thank you =)

    Reply
  3. Hi, I do believe this is a great blog. I stumbledupon it 😉 I will come back yet again since I book-marked it.
    Money and freedom is the greatest way to change, may
    you be rich and continue to help others.

    Reply
  4. You made some decent points there. I looked on the
    web for more information about the issue and found most individuals will
    go along with your views on this site.

    Reply
  5. Heya i am for the primary time here. I found this board
    and I to find It truly helpful & it helped me out much.
    I am hoping to offer one thing again and help others like you helped me.

    Reply

Leave a Comment