Create unique ids for jquery plugin instances?

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

I want to create a unique id inside the module itself, so I can off the listener when I destroy the plugin instances. How do you create these unique identifiers?

The example below clearly doesn't work - the incrementId in the destroy method always removes the 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 );

      

+1


source to share


1 answer


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

      



+1


source







All Articles