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

时间:2013-01-25 21:57:01

标签: 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 );

3 个答案:

答案 0 :(得分:6)

您的问题说明了为什么使用.on().off()比在绑定事件处理函数时使用.blur()更好。 AFAIK,当您使用.blur()时,无法取消绑定唯一事件处理程序。

以下是您可以使用的内容:

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

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

其中handlerID是唯一标识事件处理程序的文字字符串。

jQuery .off() documentation

答案 1 :(得分:3)

我在开发的框架中有类似的东西。除了我正在删除部分屏幕保护程序的事件处理。 Anywho,重点关注。你应该为你的事件命名(这就是我所做的),如下所示:

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

现在稍后,你可以在destroy上删除那个确切的事件:

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

答案 2 :(得分:0)

使用$(window).off('click.yourAppName', method);。要使off方法生效,您必须为侦听器分配on方法。 .yourAppName中有一个名称空间,在调用on时需要相同。这是为了防止插件事件干扰同一应用程序中的其他事件。