I have created a jQuery plugin which listens to window for blur events.
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?
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 );
1 Answer