2012-04-22 62 views
0

我有這個倒計時如何創建一個函數以在JavaScript插件中返回值?

(function($){ 

    var options = { 
     display_as_text  : false, 
    remaining : 0, 
     separator   : ':', 
     significant_days : 3, 
    display_on_complete : null, // id of element to display when countdown is complete 
    hide_on_complete : null // hide the timer once it hits zero 
    }; 

    $.fn.countdown = function (config_options) 
    { 
     /* 
     * Initialise 
     * 
     * Prepare data and trigger regular execution of code 
     * 
     * @param container Reference to DOM element where counter will be displayed 
     */ 
     var initialise = function (container){ 

     } 

     var update = function (seconds_remaining){   

     } 

,我需要訪問更新和重置基於值我發送的時間,但我不知道如何訪問它。下面是我如何實例化插件

$('#timer').countdown({remaining : 1000}); 

但我如何調用更新來更新秒......我試着將它設置爲一個變量,並調用它,但沒有去...任何想法

回答

0

我不確定您想要檢索剩餘秒數還是在插件中調用update函數。但無論如何,無法確定這是否包含在插件中,而無需查看完整源代碼。

您可以自定義的API隨時添加到插件,如果你操縱它,使用插件範圍內是這樣的:

$(this).data('countdown', { 
    update: update 
}); 

然後使用叫它:

$('#timer').data('countdown').update(12345); 

同樣的想法(例如,假設內部變量被稱爲seconds_remaining):

$(this).data('countdown', { 
    getSecondsRemaining: function() { 
     return seconds_remaining; 
    } 
}); 

然後:

$('#timer').data('countdown').getSecondsRemaining(); 
1

最常見的方法(即我見過)是做事的jQuery UI的風格:

  1. $(selector).plugin({...})結合插件,並允許以通常的方式鏈接。
  2. $(selector).plugin('method')作爲訪問者調用method
  3. $(selector).plugin('method', arg)調用method作爲指定arg的增變器。

所以你的情況,你會想有點參數解析邏輯添加到您的插件,讓你可以說喜歡$(selector).countdown('update', 11)事情。

您可以使用$.isPlainObjectarguments弄清楚插件是如何調用,並拉開可變長度的參數列表:

$.fn.countdown = function(options) { 
    if(!$.isPlainObject(options)) { 
     var stdarg = Array.prototype.slice.call(arguments); 
     if(stdarg[0] == 'update' && stdarg.length > 1) { 
      return this.each(function() { 
       // Set up value using stdarg[1] 
      }); 
     } 
     // ... 
    } 

    return this.each(function() { 
     // Bind as usual 
    }); 
}; 

和一個簡單的演示(當然現實是更清潔和更好的組織): http://jsfiddle.net/ambiguous/DEVBD/

相關問題