jedierikb
jedierikb

Reputation: 13089

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 );

Upvotes: 3

Views: 1357

Answers (3)

Elliot B.
Elliot B.

Reputation: 17661

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

Upvotes: 6

antonagestam
antonagestam

Reputation: 4789

Use $(window).off('click.yourAppName', method);. For the off method to take effect you have to have assigned the listener with the on method. The .yourAppName in there is a namespace and need to be the same in the call to on. This is to keep your plugin events from interfering with other events within the same app.

Upvotes: 0

Travis J
Travis J

Reputation: 82297

I have something similar in a framework I developed. Except I was removing event handling for part of a screen saver. Anywho, back on point. You should name your events (that is what I did), like this:

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

and now later, you may remove that exact event on destroy:

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

Upvotes: 3

Related Questions