【问题标题】:jQuery click event won't unbindjQuery点击事件不会解除绑定
【发布时间】:2015-10-28 09:50:40
【问题描述】:

我有一个导航,我想在单击按钮时打开它。当导航打开并且用户在导航外部单击时,我希望它关闭。我以为很容易......

我尝试通过在按钮上首先单击事件来打开导航来实现这一点。然后我在文档上添加一个触发 closeNav 方法的新点击事件。

到目前为止,一切都很好。有用。但是我的点击事件堆积起来。每次打开导航时都会添加一个新的文档单击事件。所以我添加了一个关闭点击来移除之前添加的点击事件。也尝试了 unbind,结果相同。

我的猜测它与处理程序有关,因为我使用 this.closeNav.bind(this)。但我不知道...

有什么想法吗?

headerNavigation.prototype.init = function()
{
    // Add on click event on the button that triggers toggleNavigation
    $(this.navBtn).on('click', this.toggleNavigation.bind(this));
}

headerNavigation.prototype.toggleNavigation = function(e)
{
    e.stopPropagation();
    $(this.nav).slideToggle(200);
    // Add an on click for document that triggers this.closeNav
    $(document).on('click', this.closeNav.bind(this)); 
}

headerNavigation.prototype.closeNav = function(e)
{
    console.log($(document).data('events'));
    $(this.nav).slideUp(200);
    // Now remove the on click event for document so we do not stack up on these
    $(document).off('click', this.closeNav.bind(this)); 
}

【问题讨论】:

标签: javascript jquery javascript-events event-handling


【解决方案1】:

Bind 每次调用时都会创建一个新函数。

试试这个:

headerNavigation.prototype.toggleNavigation = function(e)
{
    e.stopPropagation();
    $(this.nav).slideToggle(200);
    // Add an on click for document that triggers this.closeNav
    this._binder = this.closeNav.bind(this);
    $(document).on('click', this._binder); 
}

headerNavigation.prototype.closeNav = function(e)
{
    console.log($(document).data('events'));
    $(this.nav).slideUp(200);
    // Now remove the on click event for document so we do not stack up on these
    $(document).off('click', this._binder); 
}

【讨论】:

  • 很酷。不知道绑定每次都创建一个新函数。好像浪费了很多。也许在使用绑定时应该始终创建一个引用变量?听起来它会优化运行时。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-04
  • 2012-05-23
  • 2018-02-13
相关资源
最近更新 更多