【问题标题】:Keep "this" in bootbox callback functions在 bootbox 回调函数中保留“this”
【发布时间】:2019-12-23 10:11:22
【问题描述】:

我试图在回调中保留this 变量:

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);
    }
});

看起来很丑,有没有更好的方法?

【问题讨论】:

标签: vue.js bootbox


【解决方案1】:

你可以使用箭头函数:

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

你应该用 Babel 编译它,older browsers may not support it。如果你有回调作为变量,你可以在传递之前绑定它:

yourCb.bind(this);
bootbox.confirm("This is the default confirm!", yourCb);

【讨论】:

  • bootbox.confirm({title: XXX, callback: XXX}) 怎么样,你也有解决方案吗?
  • Bind XXX 回调:XXX.bind(this) 之前通过。
  • 你能在你的答案中添加一个例子吗?
  • 这是一个通用的JS东西。您可以控制 this 在函数中解析的内容。
猜你喜欢
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 2016-07-20
  • 2015-06-28
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
相关资源
最近更新 更多