如何创建一个函数来返回javascript插件中的值?

时间:2012-04-22 19:10:57

标签: javascript jquery

我有这个倒数计时器

(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});

但是如何调用更新来更新秒...我试图将其设置为变量并调用它但是没有去...任何想法

2 个答案:

答案 0 :(得分:1)

最常见的方法(我见过)是做jQuery-UI风格的事情:

  1. $(selector).plugin({...})绑定插件并允许以通常的方式链接。
  2. $(selector).plugin('method')调用method作为访问者。
  3. $(selector).plugin('method', arg)使用指定的method调用arg作为mutator。
  4. 因此,在您的情况下,您需要在插件中添加一些参数解析逻辑,以便您可以说出$(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/

答案 1 :(得分:0)

我不确定您是否要检索剩余的秒数或在插件中调用update函数。但无论哪种方式都不可能在没有查看完整源代码的情况下判断它是否包含在插件中。

如果你操作它,你总是可以在插件中添加一个自定义API,在插件范围内使用类似的东西:

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

然后使用:

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

同样的想法可以用于获取内部变量,例如剩余秒数,f.ex :(假设内部变量被称为seconds_remaining):

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

然后:

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