我最近开始用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'将在任何后续插件中发扬光大。任何想法如何做到这一点。
什么是divDiag?你的'this'值正在工作,但你的插件没有正确加载。 – ncksllvn
@ncksllvn divDiag是我找到的另一个插件。也许这是该插件的错误? – Dimitri
我在一个小提琴中运行了你的代码,它在divDiag上崩溃为未定义。我会说这是你的问题。如果它实际上正确加载,请确保您使用的是正确版本的jQuery。 – ncksllvn