1

我目前有两个插件,根据此处的 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();
4

1 回答 1

2

命名空间并不真正适用。唯一的要求是 2 个插件同意事件的名称。我的建议是触发事件的插件有一个带有事件名称的变量。然后消费者可以使用该名称:

// within your pluginTrigger plugin
var eventName = "pluginTriggerEvent";
$.fn.pluginTrigger.eventName = eventName;

// within your trigger method:
$(this).trigger(eventName);

// -------------------------------
// within your pluginBinder plugin init method:
$(this).on($.fn.pluginTrigger.eventName, methods.result);
于 2013-03-06T16:04:03.110 回答