简体   繁体   English

jQuery点击事件不会解除绑定

[英]jQuery click event won't unbind

I have a navigation that I want to open when I click a button.我有一个导航,当我单击一个按钮时要打开它。 When the navigation is opened and the user clicks outside the navigation I want it to close.当导航打开并且用户在导航之外单击时,我希望它关闭。 Easy I thought...容易我以为...

I try to achieve this with a click-event first on the button to open the navigation.我尝试首先在按钮上单击事件以打开导航来实现此目的。 Then I add a new click-event on the document that triggers closeNav-method.然后我在触发 closeNav 方法的文档上添加一个新的点击事件。

So far ass is well.到目前为止,屁股很好。 It works.有用。 But my click events stacks up.但是我的点击事件堆积起来。 Every time the navigation is opened a new document click event is added.每次打开导航时都会添加一个新的文档单击事件。 So I added a off click to remove the previously added click-event.所以我添加了一个关闭点击来移除之前添加的点击事件。 Also tried with unbind with same result.还尝试使用 unbind 获得相同的结果。

My guess It has to do with the handler, as I use this.closeNav.bind(this) , but I don't know...我的猜测它与处理程序有关,因为我使用this.closeNav.bind(this) ,但我不知道......

Any idea?任何想法?

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)); 
}

Bind creates new function each time you call it. Bind 每次调用它时都会创建一个新函数。

Try this:尝试这个:

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); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM