简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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