How can I remove events when a jQuery plugin is destroyed?

I need some design advice on how to clean my plugin when it gets destroyed.

I am listening for events blur

on the window, but not sure how to remove these events when the plugin is destroyed. If the plugin is applied to multiple elements, but only destroyed for one element, it should still work for other elements. What would be the correct way to design it?

(function( $ ) {

    var methods = 
    {
        init : function( options ) {
            var that = this;

            $(window).blur( function( e ) {
                that.css( "color", "red" );
                console.log( "still here" );
            });
        },

        destroy : function( ) {
            console.log( "hmmm, got to take out that blur" );
        }
    };

    $.fn.pleaseKillMe = function( method )
    {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        }
        else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        }
        else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.p5shrinkwrap' );
        }
    };

})( jQuery );

      

+3


source to share


3 answers


Your question illustrates why it is better to use .on()

and .off()

than to use .blur()

when binding event handler functions. AFAIK, it is not possible to disable a unique event handler when in use .blur()

.

You can use here:

$(window).on('blur.handlerID', function() {
    //do something event handling
});

$(window).off('blur.handlerID');

      



Where handlerID

is a literal string that uniquely identifies your event handler.

JQuery.off () Documentation

+6


source


I have something similar within a framework that I have developed. Except that I removed event handling for the screen saver portion. Anywho, back to the point. You have to name your events (this is what I did), for example:

$(window).bind("blur.SomeIdentifier", function () {//pre 1.7
$(window).on("blur.SomeIdentifier", function () {//1.7+
 //....
});

      



and now you can remove this exact event on destruction:

$(window).unbind("blur.SomeIdentifier");//pre 1.7
$(window).off("blur.SomeIdentifier");//1.7+

      

+3


source


Use $(window).off('click.yourAppName', method);

. For the off method to take effect, you need to assign a listener with the on method. .YourAppName has a namespace and must be the same when called. This means that your plugin events do not interfere with other events in the same application.

0


source







All Articles