如何在销毁jQuery插件时删除事件?

jed*_*ikb 3 jquery jquery-plugins

我需要一些关于如何在销毁时清理插件的设计建议.

blur在窗口上监听事件,但是在插件被销毁时我不确定如何删除这些事件.如果插件应用于多个元素,但仅针对一个元素销毁,则它仍应适用于其他元素.设计这个的正确方法是什么?

(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 );
Run Code Online (Sandbox Code Playgroud)

Ell*_* B. 6

你提的问题说明了为什么它是更好地使用.on().off(),比它是使用.blur()结合事件处理函数时.AFAIK,使用时无法取消绑定唯一的事件处理程序.blur().

这是你可以使用的:

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

$(window).off('blur.handlerID');
Run Code Online (Sandbox Code Playgroud)

哪个handlerID是用于唯一标识事件处理程序的文字字符串.

jQuery .off()文档