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
  • 21,114
  • 28
  • 118
  • 236
  • 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);
emix
  • 14,448
  • 10
  • 62
  • 82
  • What about bootbox.confirm({title: XXX, callback: XXX}), do you have a solution for that as well? – daisy Dec 23 '19 at 10:13
  • [Bind](http://kangax.github.io/compat-table/es5/#test-Function.prototype.bind) the `XXX` callback: `XXX.bind(this)` before passing. – emix Dec 23 '19 at 10:14
  • Can you add an example to your answer? – daisy Dec 23 '19 at 10:15
  • This is a general JS thing. You control what does the `this` resolve to in a function. – emix Dec 23 '19 at 10:17