2014-06-20 36 views
0

我最近开始用jQuery插件开玩笑,并在几个小时前开始编写我的代码。对于我来说,概念仍然很新,而且很难将它们放在一起,因此可以随意批评。在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'将在任何后续插件中发扬光大。任何想法如何做到这一点。

+0

什么是divDiag?你的'this'值正在工作,但你的插件没有正确加载。 – ncksllvn

+0

@ncksllvn divDiag是我找到的另一个插件。也许这是该插件的错误? – Dimitri

+0

我在一个小提琴中运行了你的代码,它在divDiag上崩溃为未定义。我会说这是你的问题。如果它实际上正确加载,请确保您使用的是正确版本的jQuery。 – ncksllvn

回答

0

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

我只是建立一个测试网络应用程序,所以我可以将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

请重新检查您的代码是否存在其他问题。

+0

好吧,好像第二个插件是什么导致了问题,因为我没有看到其他问题。非常感谢您的帮助! :) – Dimitri