2012-12-27 121 views
1

我有一個jQuery插件,使用流行的插件模式。該插件打開一個模態窗口,模態窗口也可以關閉。我還想添加一些更多的功能,例如通過按下退出鍵關閉窗口或通過在模式外單擊來關閉窗口。我如何將這個新代碼整合到插件中?jQuery插件 - 添加功能

注意:還要注意事件處理程序附加到使用該插件創建的Modal窗口外部的主體和文檔容器。我知道,爲了添加東西到插件,我可以將方法附加到Plugin.prototype.xxx。我能否在這裏做同樣的事情,或者我們應該以不同的方式處理這種情況?

我使用該插件
//press 'Esc' key - hide Modal 
     $('body').bind('keydown', function(e) { 
      if (e.keyCode == 27) { // "Esc" Key 
        if ($('.show').is(':visible')) { 
         $('.Close').click(); 
        } 
        return false; 
      } 
     }); 

     //click outside Modal - hide Modal 
     $(document).mouseup(function (e){ 
      var container = $(".Window"); 
      if (!container.is(e.target) && container.has(e.target).length === 0){ 
       $('.Close').click(); 
      } 
     }); 

熱門插件模式:

;(function ($, window, document, undefined) { 
    // Create the defaults once 
    var pluginName = 'defaultPluginName', 
     defaults = { 
      propertyName: "value" 
     }; 

    // The actual plugin constructor 
    function Plugin(element, options) { 
     this.element = element; 

     this.options = $.extend({}, defaults, options) ; 

     this._defaults = defaults; 
     this._name = pluginName; 

     this.init(); 
    } 

    Plugin.prototype.init = function() { 

    }; 

    $.fn[pluginName] = function (options) { 
     return this.each(function() { 
      if (!$.data(this, 'plugin_' + pluginName)) { 
       $.data(this, 'plugin_' + pluginName, 
       new Plugin(this, options)); 
      } 
     }); 
    } 

})(jQuery, window, document); 

回答

0

只需添加在init方法的代碼,但要舒爾您只選擇所需的元素。

Plugin.prototype.init = function(){ 
    this.bindEventHandlers(); 
} 
Plugin.prototype.bindEventHandlers = function(){ 
    var self = this; 

    $('body').bind('keydown', function(e) { 
     if (e.keyCode == 27) { // "Esc" Key 
       if ($('.show', self.element).is(':visible')) { 
        $('.Close', self.element).click(); 
       } 
       return false; 
     } 
    }); 

    //click outside Modal - hide Modal 
    $(document).mouseup(function (e){ 
     var container = $(".Window", self.element); 
     if (!container.is(e.target) && container.has(e.target).length === 0){ 
      $('.Close', self.element).click(); 
     } 
    }); 
} 
+0

我希望有可能的方法,我們可以傳遞布爾值和打開或關閉新代碼的功能(即開啓/關閉關閉使用「ESC」鍵模態窗口) - 類似的規定。用目前的技術建議,它似乎不是一種可能性。 – neelmeg