Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove events when destroying jQuery plugin?

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

I listen for blur events on the window, but am not sure how to remove those 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 right way to design this?

(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 );
like image 284
jedierikb Avatar asked Dec 20 '25 02:12

jedierikb


1 Answers

Your question illustrates why it is better to use .on() and .off(), than it is to use .blur() when binding event handler functions. AFAIK, it's not possible to unbind the unique event handler when you use .blur().

Here's what you can use:

$(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

like image 134
Elliot B. Avatar answered Dec 21 '25 15:12

Elliot B.