How to properly detach an event handler in jQuery

I have this jQuery function that centers an 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 is used with the jQuery Block UI plugin:

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

Each time the user interface needs to be locked, I execute the second piece of code. But when I unlock the user interface, I just delete it using the Block UI API, but I do nothing with the scroll event handler. If I lock / unlock the UI many times, I will have many event handlers registered to scroll through the event, which I think is bad. But I do not know how to solve this problem. Could you advise?

+5
source share
1 answer

jquery off

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

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

, , :

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

" " "on" "off":

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

// remove only event handlers in the ".validator" namespace
$("form").off(".validator");
+13

All Articles