从一个jQuery插件触发事件并在另一个插件中捕获它

时间:2013-03-06 15:48:15

标签: javascript jquery jquery-plugins

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

1 个答案:

答案 0 :(得分: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);