在jQuery插件中维护可链接性

时间:2014-06-20 16:09:33

标签: jquery jquery-plugins

我最近开始玩jQuery插件,几个小时前开始写我的。对我来说,概念仍然是一个新概念,并且很难将它们放在一起所以请随意批评。

我正在开发一个虚拟插件,用户可以获得有关会话到期的警报。会话“过期”后,根据给定的参数触发(自定义或默认)方法:

(function($) {
    $.fn.sessionTimeout = function(options) {

    var plugin = this;
    var lgouttime;
    var defaults = {
        refresh: 1000,
        totalTime : 2, // in seconds
        showCountDown: 'countdown',
        timeout: null
    }

    plugin.init = function() {
        plugin.settings = $.extend({}, defaults, options);
        // start countdown 
        plugin.timer();


    }   
    /* settings */      
    plugin.settings = {}
    /* timer */
    plugin.timer = function() {
        lgouttime = setInterval(function(){
            plugin.settings.totalTime = plugin.settings.totalTime-1;    
            if(plugin.settings.showCountDown != null) {
                $('#'+plugin.settings.showCountDown).html(plugin.settings.totalTime);
            }

            if(plugin.settings.totalTime==0) {
                clearInterval(lgouttime);
                if( $.isFunction(plugin.settings.timeout) ) {
                    console.log(plugin.settings.totalTime);
                    plugin.settings.timeout.call(plugin);   
                }
            }

        }, plugin.settings.refresh);
    }

    plugin.init();
    return this;

};

})(jQuery);

这将用作:

$('body').sessionTimeout({ 

    timeout: function() {
                /* do some other stuff here */
            $(this).divDiag({ // however,  'this' does not carry forward for some reason in any other plugin
                "icon" : "trash",
                "genmsg_id" : "gen_msg",
                "mainID" : "sessionTimeout",
                "contents" : 'Session expired.' 
            });         


    }
});

现在一切正常,但无法在任何后续插件中继续使用'this'。关于如何做到这一点的任何想法。

1 个答案:

答案 0 :(得分:0)

好。忽略我的其他答案(已删除),因为您的特定加载项似乎只需要附加一个实例(到正文)。这种方式使得使用jQuery插件代码毫无意义,因为您没有针对附加元素的任何特定目标。它可以很容易地成为jQuery实例上的静态扩展。

我只是构建一个测试web-app ,这样我就可以将Visual Studio调试器的功能发挥到极致并找到......

...您的样本效果很好:

$(this)确实贯穿了plugin.settings.timeout来电。但是,您尝试在其上访问的其他divDiag扩展名在示例代码中不存在,但如果我将其替换为更简单的扩展,则可以正常工作:

$(function () {
    $('body').sessionTimeout({
        showCountDown: "countdown",
        timeout: function () {
            alert(this);
            /* do some other stuff here */
            $(this).append("<h1>I am body!</h1>")
        }
    }).css("background-color", "yellow");  // Chains here too
});

结果:

enter image description here

请在其他地方重新检查您的代码。

相关问题