我创建了一个 jQuery 插件,它监听窗口的模糊事件。
我想在插件本身内部创建一个唯一的 id,以便在销毁插件实例时可以关闭侦听器。我应该如何创建这些 uniqueIds?
下面的示例显然不起作用——destroy 方法中的 incrementId 总是从最后一个插件实例中删除模糊。
(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 );