为jQuery插件实例创建唯一的ID? [英] create unique ids for jquery plugin instances?

查看:100
本文介绍了为jQuery插件实例创建唯一的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个jQuery插件,用于侦听窗口中的模糊事件.

I have created a jQuery plugin which listens to window for blur events.

我想在插件本身内部创建一个唯一的ID,这样我可以在监听器关闭时我销毁插件的实例.我应该如何创建这些uniqueId?

I want to create a unique id inside of the plugin itself so I can off the listener when I destroy instances of the plugin. How should I create these uniqueIds?

以下示例显然不起作用-destroy方法中的增量ID始终会消除最后一个插件实例中的模糊.

The example below clearly does not work -- incrementId in the destroy method is always removing blur from the last plugin instance.

 (function( $ ) {

    var incrementId = 0;

    var methods = 
    {
        init : function( options ) {
            var that = this;
            incrementId += 1;
            $(window).on( "blur.pleaseKillMe" + incrementId, function( e ) {
                that.css( "color", "red" );
            });
        },

        destroy : function( ) {
            console.log( "and... " + incrementId );
            $(window).off( "blur.pleaseKillMe" + incrementId );
        }
    };

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

推荐答案

incrementId += 1;
this.data('id', incrementId);
...
$(window).off('blur.pleaseKillMe' + this.data('id');

这篇关于为jQuery插件实例创建唯一的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆