2013-07-04 29 views
0

我爲jQuery製作了一個簡單的插件,它爲兩個給定的日期選擇器設置了minDate和maxDate。 現在我想擴展它並添加一個函數來設置日期。jQuery自定義插件 - 如何添加功能

JS

(function($) { 

    $.fn.dateRange = function(){ 
     return this.each(function() { 
      var from, to; 
      var self = $(this); 
      var selectedDate; 
      $("input",this).prop('readonly', true); 
      from = $('.from',this); 
      to = $('.to',this); 
      from.datepicker({ 
       onClose:function(selectedDate) { 
        $(this).siblings(".to").datepicker("option", "minDate", selectedDate); 
       } 
      }); 

      to.datepicker({ 
       onClose:function(selectedDate) { 
        $(this).siblings(".from").datepicker("option", "maxDate", selectedDate); 
       } 
      }); 
      //add a function 
      this.setDate = function (f, t) { 
       from.datepicker("option",{ 
        defaultDate: new Date(f), 
        maxDate: new Date(t) 
       }).val(f); 

       to.datepicker("option",{ 
        defaultDate: new Date(t), 
        minDate: new Date(f) 
       }).val(f); 
      }; 
     }); 
    }; 

})(jQuery); 


$("div.dateRange").dateRange(); 

//later 

$("#label1").dateRange().setDate("07/02/2013","07/06/2013"); 

控制檯說:未捕獲的類型錯誤:對象[對象的對象]無方法 '的setDate'。什麼是向插件添加更多功能的最佳方式?

這裏是一個jsbin:http://jsbin.com/acovuj/2/edit

+1

http://iainjmitchell.com/blog/?p=360這篇文章解釋了一個很好的例子。 – Tommi

+1

這樣做的一種方法就像jQuery UI(http://api.jqueryui.com/button/#method-enable),您將方法名稱作爲字符串傳遞,然後處理該方法以調用內部函數。這基本上是Tommi的鏈接解釋! –

+0

將'this.setDate'更改爲'self.setDate',它應該可以工作。然而,這不是一個好的方法,你應該看看[jQuery Boilerplate](http://jqueryboilerplate.com/)以獲得更好的設計模式。 – mekwall

回答

1

有很多方法可以做到這一點,正如許多評論人士指出。

這裏有一個樣板,我覺得簡單易懂:

;(function($) { 

    function init(options) { 
     return this.each(function() { 
      // your initialization comes here 
      // ... 
     }); 
    } 

    function setDate(date1, date2) { 
     // your implementation comes here 
     // ... 
    } 

    var methods = { 
     init: init, 
     setDate: setDate 
    }; 

    $.fn.dateRange = 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.datePicker'); 
     } 
    }; 
})(jQuery); 

在此設置調用setDate方法是這樣的:

$("#label1").dateRange("setDate", "07/02/2013", "07/06/2013"); 

也就是說,方法的名稱setDate你實際上想打電話是dateRange的一個參數,你不要直接調用它。

我不記得我看過這個例子的地方,但我一直在使用它,它對我很好。對於使用此技術的完整但簡單的示例,我前幾天創建了here's a jQuery plugin。我希望這會有所幫助。