触发并绑定到自定义事件?

时间:2012-08-02 15:10:57

标签: javascript jquery-plugins jquery

我正在尝试编写一个基本对话框。我希望能够指定一个链接元素,在单击时将启动一个对话框。

我在对话框HTML中使用数据属性指定此行为:

<a id="launch-dialog" href="#"></a>
<div class="dialog" data-behavior="dialog" data-trigger="#launch-dialog">
  <!-- dialog html -->
</div>

$(function(){
  $("[data-behavior='dialog']").dialog();
});

实际的jQuery扩展是我遇到麻烦的部分。未正确触发正文上的'dopen'事件,或者未正确设置事件绑定。 data-trigger上的点击事件肯定会被触发并被收听。任何想法,为什么我从来没有看到“检测到开放”的日志?

(function($) {
  var methods = {
    init: function(options) {

      if (this.data('trigger')) {
        // Add an event listener which causes the dialog to
        // open when the correct link is clicked.
        $(this.data('trigger')).on('click', function(e) {
          e.preventDefault();
          // Trigger a global dialog open event which the dialog can subscribe to.
          $('body').trigger('dopen');
        });
      }
    },
    // Various other methods not shown.
  };

  $.fn.dialog = function(method) {

    // Method handling code not shown...

    // Add handlers for custom events triggered on the body element.
    $('body').bind('dopen', function(e) {
      // This never happns:
      console.log("Open detected");
    });

  };
})(jQuery);

1 个答案:

答案 0 :(得分:0)

我无意中没有提供足够的信息来解决问题。

我在哪里

# Method handling code not shown...

在问题代码中,真实代码具有以下内容:

// If it corresponds to a method defined in the method object.
if (methods[method]) {
  return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
// Else, if we pass in an object and 
} else if ( _.isObject(method) || !method ) {
  return methods.init.apply( this, arguments );
} else {
  $.error( 'Method ' +  method + ' does not exist on jQuery.doalog' );
}

如您所见,该代码段有三种可能的路径:

  1. 返回方法调用的结果,
  2. 返回方法调用的结果,
  3. 提出异常。
  4. 控制流在这些路径中变得捷径,并且没有到达我尝试绑定侦听器的行。当然,永远不会解雇未绑定的侦听器。

    解决方案是将绑定移动到初始化方法中:

      var methods = {
        init: function(options) {
    
          // Add handlers for custom events triggered on the body element.
          $('body').bind('dopen', function(e) {
            // Now it works!
            console.log("Open detected");
           });
    
          if (this.data('trigger')) {
            // Add an event listener which causes the dialog to
            // open when the correct link is clicked.
            $(this.data('trigger')).on('click', function(e) {
              e.preventDefault();
              // Trigger a global dialog open event which the dialog can subscribe to.
              $('body').trigger('dopen');
            });
          }
        },
        // Various other methods not shown.
      }