在我构建的这个自定义区域中,coffeescript's的胖箭头是如何转换成Javascript的?

Marionette js - how does coffeescript's fat arrow translate to Javascript in this custom region I'm building?

本文关键字:何转换 转换 Javascript 自定义 构建 区域 coffeescript      更新时间:2023-09-26

在这个视频教程https://www.youtube.com/watch?v=hBVYDVy3QNI的22:30,作者用coffeescript做了一些我无法翻译成Javascript的东西。他使用一个大箭头从内部回调中维护自定义区域的上下文。这样,他就能从一个对话框内调用该区域的close回调吗?如何在Javascript中实现呢?

这是我的自定义区域尝试,但它在调用this. closedialog()时失败,因为"this"指的是对话框而不是区域:

    var DialogRegion = Backbone.Marionette.Region.extend({
        onShow: function (view) {
            this.$el.dialog({
                modal: true,
                resizable: false,
                draggable: false,
                width: "600px",
                close: function (e, ui) {
                        this.closeDialog()//This doesn't work.  Wrong context.  Need outer DialogRegion context?                
                }
            })
        },        
        closeDialog: function () {
            this.close();
            this.$el.dialog("destroy");
        }
    }); 

如果你可以假设一个相当现代的JavaScript,那么你可以使用Function.prototype.bind:

bind()方法创建了一个新函数,当调用该函数时,将其this关键字设置为提供的值[…]

就像这样:

close: function (e, ui) {
    this.closeDialog();
}.bind(this)

你在使用木偶,所以你在使用主干,这意味着下划线是可用的。这意味着如果您不想使用本机bind,则可以使用_.bind:

close: _(function (e, ui) {
    this.closeDialog();
}).bind(this)

你正在使用jQuery-UI,所以你应该有$.proxy可用。$.proxy的用途与_.bind相同,您可以这样使用它:

close: $.proxy(function(e, ui) {
    this.closeDialog();
}, this)

"classic"选项是elclors在注释中提到的:

onShow: function (view) {
    var _this = this;
    this.$el.dialog({
        //...
        close: function (e, ui) {
            _this.closeDialog()
        }
    });
}

这四个在功能上都等同于你在CoffeeScript视频中看到的close: (e, ui) => ...