3

我需要一些关于如何在插件被破坏时清理它的设计建议。

我在窗口上监听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 );
4

3 回答 3

6

您的问题说明了为什么使用.on()and.off().blur()在绑定事件处理函数时使用更好。AFAIK,您使用.blur().

这是您可以使用的:

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

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

WherehandlerID是唯一标识您的事件处理程序的文字字符串。

jQuery .off() 文档

于 2013-01-25T22:00:38.707 回答
3

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

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

现在稍后,您可以在销毁时删除该确切事件:

$(window).unbind("blur.SomeIdentifier");//pre 1.7
$(window).off("blur.SomeIdentifier");//1.7+
于 2013-01-25T22:01:43.427 回答
0

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

于 2013-01-25T22:02:51.197 回答