user2678106
user2678106

Reputation:

jQuery custom event listener

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

Upvotes: 1

Views: 2559

Answers (1)

adeneo
adeneo

Reputation: 318182

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.

Upvotes: 4

Related Questions