I need some design advice on how to clean up my plugin when it is destroyed.
I listen for blur events on the window, but am not sure how to remove those events when the plugin is destroyed. If the plugin is applied to multiple elements, but only destroyed for one element, it should still work for other elements. What would be the right way to design this?
(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 );
Your question illustrates why it is better to use
.on()and.off(), than it is to use.blur()when binding event handler functions. AFAIK, it’s not possible to unbind the unique event handler when you use.blur().Here’s what you can use:
Where
handlerIDis a literal string that uniquely identifies your event handler.jQuery .off() documentation