在同一范围内访问单击的元素和 "this" class 引用

Accessing clicked element and "this" class reference in the same scope

我有这段代码是用 coffeescript 写的(抱歉..)

_this = this
$('body').on 'click', '.open-modal', =>
    _this.modalId = $(this).attr('data-modal-id')
    _this.modalEl = $( '#' + _this.modalId )
    _this.modalAction = $(this).attr('data-action')

    _this.openModal()

有没有一种方法可以访问点击的元素 ('.open-modal'),同时为 Class 而不是点击的元素保留 this 关键字。

基本上我想达到这样的效果

$('body').on 'click', '.open-modal', (el) =>
    this.modalId = $(el).attr('data-modal-id')
    this.modalEl = $( '#' + this.modalId )
    this.modalAction = $(el).attr('data-action')

    this.openModal()

有什么办法吗?

如果您使用的是 ECMAScript 6,则箭头函数语法 (() => {}) 可以执行此操作,但您必须从事件对象中获取元素。我认为 CoffeeScript 可能会将其 () => {} 语法转换为函数的 ES5 版本,但可能不会这样做(我认为这取决于您的编译器设置)。

$('body').on('click', '.open-modal', (evt) => {
    this.modalId = $(evt.target).attr('data-modal-id');
    this.modalEl = $('#' + this.modalId);
    this.modalAction = $(evt.target).attr('data-action');
});

如果您不能使用它,常见的模式是将 this 保存为 self,然后在其他范围内使用它。这不依赖于任何特定的编译器帮助。

var self = this;
$('body').on('click', '.open-modal', function () {
    this.modalId = $(this).attr('data-modal-id')
    this.modalEl = $('#' + self.modalId)
    this.modalAction = $(this).attr('data-action')
});

最后,如果您真的想要它,您可以将回调包装在另一个函数中,根据需要进行设置。

$('body').on('click', '.open-modal', (function (self) {
    return function () { 
        (function (el) {
            this.modalId = $(el).attr('data-modal-id');
            this.modalEl = $('#' + this.modalId);
            this.modalAction = $(el).attr('data-action');
        }).call(self, this);
    };
})(this));

虽然这有点愚蠢和矫枉过正。它使用自调用函数将 this 限定为自身,returns 一个函数,然后包装另一个使用 call 指定 this 并将元素作为参数传递的函数。