lejahmie
lejahmie

Reputation: 18253

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.

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.

My guess It has to do with the handler, as I use this.closeNav.bind(this), but I don't know...

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

Upvotes: 0

Views: 116

Answers (1)

Kesha Seyfert
Kesha Seyfert

Reputation: 38

Bind creates new function each time you call it.

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

Upvotes: 1

Related Questions