Rajesh Yogeshwar
Rajesh Yogeshwar

Reputation: 2179

jquery stop delegated event from being called twice

My JS looks something like this

$(document).ready(function(){
    menuClickHandler();
});

I have ajax based menu, menuClickHandler is used to make it work and resides in a separate JS file. menuClickHandler associates other functions that are associated to menu item. On click of menu item it calls a function associated with the menu item. Lets say I have menu item Jump and a function JumpHandler associated with it. Within JumpHandler there is one simple function as follows

functionA() {
    $("div.tree").on("click", ".branch", function(event) {
        event.stopPropagation();
        //some code
    });
}

Scenario: When the page is first loaded everything is fine, when I click on Jump functionA' gets called and everything works fine. Now if click some other menu item and then click onJumpagain,JumpHandleris called again and hencefunctionA` gets called again resulting in click event on branch being bound twice. Can anyone tell me how do I remove/undelegate the delegated click event so that there is only click event bound to branch.

jQuery version: v2.1.1

Upvotes: 4

Views: 933

Answers (3)

Vegeta
Vegeta

Reputation: 1317

Because Once the function is called you have initialize a function in jquery which will execute without calling the function again. So before calling any function just turn off the jquery function

example:

$("div.tree").off("click", ".branch" );
functionA();

$("div.tree").off("click", ".branch" );
functionB();

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can use .one() instead of .on()

Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

Code

$("div.tree").one("click", ".branch", function(event) {
    event.stopPropagation();
    //some code
});

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68393

if for some reason you have to bind click event inside functionA, then you can try off

functionA() {
    $("div.tree").off("click", ".branch" );
    $("div.tree").on("click", ".branch", function(event) {
        event.stopPropagation();
        //some code
    });
}

or else you can do this binding outside the functionA since it is attach the event handlers to future branch elements regardless of when you invoke functionA

if you want to ensure that event is only fired once, then

functionA() {
    $("div.tree").on("click", ".branch", function(event) {
        event.stopPropagation();
        //some code
       $("div.tree").off("click", ".branch" );
    });
}

Upvotes: 1

Related Questions