Javascript (jquery) - Multiple Handlers attached to one event: How to detach only one?

前端 未结 3 1202
野的像风
野的像风 2021-01-13 10:07

In this module I\'m working on I have a listener to a \'resize\' event in the window. Every time the module is ran, I need to check if there\'s already a listener registere

3条回答
  •  再見小時候
    2021-01-13 10:42

    Here 2 different suggestions. You can either give a namespace to your event or pass a none anonymous function when binding.

    Example when using namespace :

    $(window).on('resize.event1', function(){});
    $(window).on('resize.event2', function(){});
    
    //Only turn off event 2
    $(window).off('resize.event2');
    

    jQuery allow you to identify your event. This behaviour is called namespace. The current event and the event name must be separate by a dot. In that case, i am binding 2 resize event (left side of the dot), one with the name event1 and the other with event2.

    By identifying the event, you can remove (or trigger) single event when an object have multiple of the same event.

    $(window).trigger('resize'); //Trigger both;
    $(window).trigger('resize.event2'); //Trigger event2;
    

    Example using named functions :

    $(window).on('resize', function1);
    $(window).on('resize', function2);
    
    //Only turn off event 2
    $(window).off('resize', function2);
    

    Associating a none anonymous function allow you to remove the event if the passed function match the current event function. Because function2 === function2, only the second function will be remove since function1 !== function2!

提交回复
热议问题