1

I have following code:

myCustomMethod(function(){
    $(document).on('click','#element',function(){
        console.log('First call');
    });
});

setTimeout(function(){
    myCustomMethod(function(){
        $(document).on('click','#element',function(){
            console.log('Second call, event first call should be destroyed');
        });
    });
},2000);


function myCustomMethod(funcn){
    funcn();            
}

When I test with my browser, I clicked #element console show up First call

but after 2 sec I click again it shows

First call
Second call, event first call should be destroyed

I want to remove the event listener if it is modified (the part below)

Old

$(document).on('click','#element',function(){
    console.log('First call');
});

New

$(document).on('click','#element',function(){
    console.log('Second call, event first call should be destroyed');
});

only fires console.log('Second call, event first call should be destroyed');

thanks a lot

1 Answer 1

4

Adding an event handler does not remove previous event handlers, it just adds more, and that's why the old event handler is not removed.

You could use off() to remove event handlers in jQuery

$(document).on('click.custom', '#element', function(){
    console.log('First call');
});

setTimeout(function(){
    $(document).off('click.custom').on('click.newclick','#element',function(){
        console.log('Second call, event first call should be destroyed');
    });
},2000);

to remove all previous handlers for a specific event you'd do

$(document).off('click');

The function you're using makes no sense at all, and note that you can namespace events to remove specific events at a later time.

Sign up to request clarification or add additional context in comments.

6 Comments

Then you'd have to remove them, they don't magically dissapear when you attach new ones
Can I find all handlers which called inside a function?
As long as they are attached with jQuery's on(), you can use off() to remove them, just read the answer above.
I mean find click.custom and save it to a variable, then use off() to remove it if new handler triggered
Well, click.custom is just a way to namespace, you could do click.myclick, click.santa or anything else you'd like, it's just so you don't remove all clicks, but only the click that has that name, that way it's easier to manage. If you need to remove all clicks, just use off('click').
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.