2012-08-02 62 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. 
    }