2013-07-04 2 views
0

jQuery에 대한 간단한 플러그인을 만들었습니다.이 플러그인은 주어진 두 datePickers에 대해 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 '. 플러그인에 더 많은 기능을 추가하는 가장 좋은 방법은 무엇입니까? 많은 의견에 의해 지적 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 보일러 플레이트] (http://jqueryboilerplate.com/)를 살펴 봐야합니다. – mekwall

답변

1

는,이 작업을 수행하는 방법에는 여러 가지가 있습니다 : 여기

는 jsbin이다.

이 설정에서
;(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 며칠 전에 만들었습니다. 나는 그것이 도움이되기를 바랍니다.

관련 문제