2012-08-02 88 views
1

我想写一个基本的对话框。我希望能够指定一个链接元素,它将在点击时启动一个对话框。触发并绑定到自定义事件?

I'n使用数据指定此行为属性对话框中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); 

回答

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. 引发异常。

控制流在这些路径中变得越来越快捷,并且未达到我尝试绑定侦听器的那一行。当然,一个未绑定的侦听器永远不会被触发。

的解决方案是移动的结合成初始化方法:

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. 
    }