Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly detach event handler in jQuery

I have this jQuery function that centers element vertically with scroll support:

    $.fn.center = function () {
        var self = this;
        this.css("position", "absolute");
        this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");            
        $(document).on("scroll", function () {
            self.center();
        });
        return this;
    };

and it's used along with jQuery Block UI plugin:

    $('#cph')
        .block(finalOptions)
        .find('.blockUI.blockMsg')
        .center();

Every time a UI needs to be blocked, I execute second code snippet. But when I unblock UI, I just simply remove it with Block UI API, but I do nothing with scroll event handler. If I block/unblock UI many times, I'll have many event handlers registered to scroll event - which I guess is bad. But I don't know how to properly address that issue. Could you advise?

like image 670
dragonfly Avatar asked Jan 28 '13 09:01

dragonfly


People also ask

Which jQuery function removes previously attached event handlers on the element?

The . off() method removes event handlers that were attached with .

Can event handlers be removed?

Go to the objects tab, view the Document object (don't click on edit) and scroll down to Event Handlers. Select the one to delete and press delete.

Should you always remove event listeners?

The event listeners need to be removed due to following reason. Avoid memory leaks, if the browser is not handled it properly. Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.


1 Answers

use jquery off

// assume you have a method for reuse purpose
function YourFunction(){
    // do something
};

$(document).on("scroll", YourFunction);
$(document).off("scroll", YourFunction);

Note that anonymous function won't work in this case unless you want to detach all event handlers:

$(document).off("scroll");

You can also specify a "namespace" when "on" and "off" events:

// delegate events under the ".validator" namespace
$(document).on("click.validator", function(){
    // do something
});

// remove only event handlers in the ".validator" namespace
$("form").off(".validator");
like image 58
phnkha Avatar answered Nov 14 '22 22:11

phnkha