我目前有两个插件,根据此处的 jquery 指南编写:http: //docs.jquery.com/Plugins/Authoring
从一个插件引发命名空间事件然后在另一个插件中捕获它的最佳实践方法是什么?我在这里的 jsfiddle 中设置了一个简化版本:http: //jsfiddle.net/cMfA7/ - HTML 和 Javascript 如下:
HTML:
<div id="container">
<button id="click">Click Me!</button>
<div id="result"></div>
</div>
Javascript:
/* ===========================
Plugin that triggers event:
=========================== */
(function( $ ){
var methods = {
init : function( options ) {
return this.each(function(){
$("#click").bind('click.pluginTrigger', methods.trigger);
});
},
trigger : function( ) {
// TODO: Trigger to go here?
}
};
$.fn.pluginTrigger = 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.tooltip' );
}
};
})( jQuery );
/* ===========================
Plugin that handles event:
=========================== */
(function( $ ){
var methods = {
init : function( options ) {
return this.each(function(){
// TODO: Binding on pluginTrigger event to go here (and call methods.result method below)?
});
},
result : function( ) {
$("#result").text("Received!");
}
};
$.fn.pluginBinder = 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.tooltip' );
}
};
})( jQuery );
/* ===============
Initialisation
=============== */
$("#container").pluginTrigger();
$("#container").pluginBinder();