2012-02-03 2 views
1

대상 날짜를 설정하는 간단한 카운트 다운 타이머 인 첫 jQuery 플러그인을 작성하고 있습니다. 목표는 제공된 목표 날짜 & 시간까지 카운트 다운하는 일반 텍스트 시계를 얻는 것입니다. 내 인생에서 나는 실제로 카운트 다운 그래서 플러그인 내에서 setTimeout 또는 setInverval을 사용하는 방법을 알아낼 수 없습니다. stackoverflow 및 기타 소스를 통해 하루 종일 파고 들지만 솔루션을 찾을 수 없으므로 사과하지 않습니다. 여기 setTimeout 또는 setInterval을 사용하는 jQuery 플러그인

내가 가지고있는 작업은 다음과 같습니다.

(function($){ 

    $.fn.clock = function(options) { 

    // ESTABLISH DEFAULTS 
    var settings = $.extend({ 
     'target' : '07/21/2013 09:00:00', // mm/dd/yyyy hh:mm:ss 
    }, options); 

    return this.each(function() {   

     // calculate milliseconds to target 
     tarDate = new Date(settings.target); 
     dateNow = new Date(); 
     amount = tarDate.getTime() - dateNow.getTime(); 
     delete dateNow; 

     // set label 
     label = settings.title; 

     // generate output 
     if(amount <= 0) { 
     out = '000:00:00:00'; 
     } else { 
     td = 0; th = 0; tm = 0; ts = 0; out = ''; // reset everything 
     amount = Math.floor(amount/1000);   // kill the milliseconds 
     td  = Math.floor(amount/86400);  // calculate days to target 
     amount = amount%86400;     // convert amount to days 
     th  = Math.floor(amount/3600);   // calculate hours to target 
     amount = amount%3600;      // convert amount to hours 
     tm  = Math.floor(amount/60);   // calculate minutes to target 
     amount = amount%60;      // convert amount to minutes 
     ts  = Math.floor(amount)+1;   // calculate seconds to target 

    out += (td<=99?'0':'') + (td<=9?'0':'') + td + ':'; 
    out += (th<=9?'0':'') + th + ':'; 
    out += (tm<=9?'0':'') + tm + ':'; 
    out += (ts<=9?'0':'') + ts; 
     } 

     // assemble and pump out to dom 
     $(this).html(out); 

     // set refresh rate 
     ?????? 

    }); 

    }; 
})(jQuery); 

답변

2

플러그인 작성을위한 흥미로운 패턴을 보려면 this link을 확인하십시오. 기본적으로 당신이해야 할 것은 당신의 시계 업데이트하는 "방법"을 제공 할 수 있습니다 :에서 (

$(yourselector).clock("update"); 

: 다음

(function($){ 

    function updateClock(element) { 
     var settings = element.data("settings"); 
     // Your update logic goes here 
    } 

    $.fn.clock = function(options) { 
     if (options === 'update') 
      return updateClock(this); 
     // Other methods, if any 
     else if (typeof options !== 'object') 
      throw 'Unknown method'; 

     // ESTABLISH DEFAULTS 
     var settings = $.extend({ 
      'target' : '07/21/2013 09:00:00', // mm/dd/yyyy hh:mm:ss 
     }, options); 

     // Save your settings for later access 
     this.data("settings",settings); 

을, 당신이 요소를 업데이트 할 때마다, 당신은이 방법으로 호출 외부; updateClock이 범위에서 액세스 할 수있는 경우, 당신은 효율성을 위해 직접 호출 할 수 있습니다 그냥 필요한 경우

마지막으로, 당신은 setTimeout 또는 setInterval을 구성해야) $()의 요소를 포장해야합니다.. 필자는 setTimeout을 선호 할 것입니다. 왜냐하면 필요한 경우 시계를 멈추거나 다시 시작할 수 있기 때문입니다. 어쩌면 체크 덧붙일 당신의 updateClock의 끝이 추가 :

setTimeout(function() { updateClock(element); }, settings.refreshRate); 
+0

어떻게 작동하는지 알 수 있지만 updateClock 함수에 전달되는 플러그인 옵션은 어떻게 얻을 수 있습니까? $ .fn.clock에서 setTimeout을 사용할 수 있습니까? 그건 그렇고 좋은 기사, 링크 주셔서 감사합니다. – codybuell

+0

@codybuell 내 업데이트 된 답변보기. 기본적으로 요소를 만들 때 옵션을 저장 한 다음 메서드를 호출 할 때'data' 함수를 사용하여이를 검색합니다 (개별 시계에서 사용되는 경우 상태를 유지하는 데에도 사용할 수 있음). 요소를 만든 직후 처음으로 update funcion을 호출 할 수 있으며, 결국 당신을 위해'setTimeout'을 호출 할 것입니다. 아니면 그냥 직접 전화해라. – mgibsonbr

2

내가 당신을 호출하고있는 함수를 호출에서는 setTimeout이 될 필요가 함수 내에서는 setTimeout 것으로 믿습니다 후 한때 조건 설정을 가지고 0에 도달합니다 clearTimeout will go off http://jsfiddle.net/qUYQN/

+0

나는 그것이 자바 스크립트 함수로 잘 작동 할 수 있습니다하지만 난 jQuery 플러그인 내에서 그 작업을 수행하는 방법을 잘 모르겠어요. – codybuell