在启动箱回调函数中保留“ this”

时间:2019-12-23 10:11:22

标签: vue.js bootbox

我正在尝试在回调中保留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);
    }
});

它看起来很丑,还有更好的方法吗?

1 个答案:

答案 0 :(得分: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);