javascript - jQuery off() 在使用 bind 时不是取消绑定(bind)事件

标签 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();

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

最佳答案

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

如果您的应用程序中只有几个气泡,您可以并且根本不使用this。这将消除很多关于 this 指的是什么的混淆,并确保每个 bubble 保留对其自己的 click 函数的引用,该函数可以用于根据需要删除事件:

function bubble(content, triggerElm) {
    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();

看看这如何让您免于使用诸如 .bind() 和下划线前缀方法之类的发明。

关于javascript - jQuery off() 在使用 bind 时不是取消绑定(bind)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800850/

相关文章:

javascript - 控制台.log();如何调试javascript

javascript - 如何显示上传进度 jQuery、Ajax、PHP

javascript - 将 2 创建的元素连接到 html 属性中

jquery - 单击元素时绘制元素的边界框 RaphaelJS

javascript - PHP 等效于 JavaScript 绑定(bind)

javascript - jQuery 事件处理逻辑

javascript - 如何将 Angular 7 应用程序包含在现有的 html 文件和网站中?

javascript - 图表师 : remove all grid lines but display axis

javascript - Node.js base64 对下载的图像进行编码以在数据 URI 中使用

javascript - Object.prototype 和 bind() 方法如何协同工作