2

I'm trying to keep this variable in the callback:

var that = this

// type1
bootbox.confirm("This is the default confirm!", function(result){ 
    console.log(that.whatever); 
});

// type2
bootbox.confirm({
    message: "This is a confirm with custom button text and color! Do you like it?",
    callback: function (result) {
        console.log(that.whatever);
    }
});

It looks ugly, is there any better way to do it?

daisy
  • 22,498
  • 29
  • 129
  • 265
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Quentin Dec 23 '19 at 10:18

1 Answers1

1

You can use an arrow function:

bootbox.confirm("This is the default confirm!", result => { 
    console.log(this.whatever); 
});

You should compile this with Babel though, older browsers may not support it. If you have the callback as a variable, you can bind it before passing:

yourCb.bind(this);
bootbox.confirm("This is the default confirm!", yourCb);
Mike Doe
  • 16,349
  • 11
  • 65
  • 88