使用bind时,jQuery off()不会解除绑定事件

Elf*_*lfy 8 javascript jquery bind jquery-events

function bubble(content, triggerElm){
  this.element = $('<div class="bubble" />').html(content);
  this.element.css(.....) // here is positioned based on triggerElm
}

bubble.prototype.show = function(){
  $(document).on('click', this._click.bind(this));
  this.element.css(....)
};

bubble.prototype.hide = function(){
  $(document).off('click', this._click.bind(this));
  this.element.css(....)
};  

bubble.prototype._click = function(event){
  console.log('click', this);

  if(this.element.is(event.target) || (this.element.has(event.target).length > 0))
    return true;

  this.hide();
};

var b = new bubble();
b.show();
b.hide();
Run Code Online (Sandbox Code Playgroud)

我一直看到在控制台中点击,因此点击不会解除绑定.但是,如果我删除bind()调用,则单击是未绑定的.有谁知道为什么?我需要一种能够在我的测试函数中更改"this"的方法,这就是我使用bind()的原因

Jos*_*ier 5

一种选择是 命名事件:

$(document).on('click.name', test.bind(this));
$(document).off('click.name');
Run Code Online (Sandbox Code Playgroud)

这里的例子


JLR*_*she 5

问题是this._click.bind()每次调用时都会创建一个新函数.为了分离特定的事件处理程序,您需要传入用于创建事件处理程序的原始函数,并且这不会发生在此处,因此不会删除处理程序.

如果bubble您的应用程序中只有几个s,您可以去道格拉斯克罗克福德的路线而根本不使用this.这将消除许多关于this所指的内容的混淆,并确保每个都bubble保留对其自身click功能的引用,可用于根据需要删除事件:

function bubble(content, tiggerElm) {
    var element = $('<div class="bubble" />').html(content);
    element.css(.....); // here is positioned based on triggerElm

    function click(event) {
        console.log('click', element);
        if (element.is(event.target) || 
            element.has(event.target).length > 0) {
            return true;
        }
        hide();
    }

    function show() {
        $(document).on('click', click);
        element.css(....);
    }

    function hide() {
        $(document).off('click', click);
        element.css(....);
    } 

    return {
        show: show,
        hide: hide
    };
}

var b1 = bubble(..., ...);
b1.show();

var b2 = bubble(..., ...);
b2.show();
Run Code Online (Sandbox Code Playgroud)

看看这是如何使您免于使用类似.bind()和下划线前缀方法的设计.