[英]jQuery widget factory _destroy method
我正在尝试创建一个计时器小部件,该计时器小部件可以用几秒钟的时间进行初始化,然后在任何时候通过使用新的“秒数”进行新的呼叫以从倒数开始进行重置。 到目前为止,我已经创建了计时器并进行倒计时。
我想做的是先在_create方法内部调用_destroy方法,以删除元素上已经存在的计时器,并使用window.clearInterval来停止重新添加计时器。 在_start方法中设置了this.interval,然后在_destroy方法中对其进行了引用,但我认为问题在于this.interval的范围。
到目前为止,这就是我所拥有的,但是我的_destroy方法似乎并未清除间隔,并且我不知道为什么。
$.widget('time.countdown', {
options : {
remaining : (2 * 24 * 60 * 60 * 1000),
updatefreq: 1000
},
_create : function () {
'use strict';
this._destroy();
},
_start: function () {
'use strict';
var secs = this.options.remaining;
this.interval = window.setInterval((function (elem, secs) {
return function () {
secs -= 1;
var days = Math.floor(secs / (24 * 60 * 60)),
div_hr = secs % (24 * 60 * 60),
hours = Math.floor(div_hr / (60 * 60)),
div_min = secs % (60 * 60),
minutes = Math.floor(div_min / 60),
div_secs = div_min % 60,
seconds = Math.ceil(div_secs),
time_parts = {
"d": days,
"h": hours,
"m": minutes,
"s": seconds
},
tstring = '',
c;
for (c in time_parts) {
if (time_parts.hasOwnProperty(c)) {
tstring += time_parts[c] + c + ' ';
}
}
elem.html(tstring);
};
}(this.element, secs)), this.options.updatefreq);
},
_destroy: function() {
'use strict';
if (this.interval !== undefined) {
window.clearInterval(this.interval);
}
this.element.html('');
}
});
谁能对此有所启发?
您的代码有些奇怪的是,没有调用“ private” _start()
函数,而是调用了nvm。
您应该将public reset()
函数添加到:
remaining
值, _start()
函数 然后应在需要时调用此reset()
函数。 看看下面的代码和解释:
(function($) {
$.widget('time.countdown', {
options : {
remaining : (2 * 24 * 60 * 60 * 1000),
updatefreq: 1000
},
_create : function () {
'use strict';
this._start();
},
_setOption: function(key, value) {
key == 'remaining' ?
this.reset(value) :
this._super(key, value);
},
_start: function () {
'use strict';
// your countdown code
},
reset: function(remaining) {
// You should perform some checks on the given value
this.options.remaining = remaining;
this._destroy();
this._start();
},
_destroy: function() {
'use strict';
if (this.interval !== undefined)
window.clearInterval(this.interval);
this.element.html('');
}
});
})(jQuery);
请注意, _create()
函数在创建时仅被调用一次。 因此,如果您将插件多次应用在同一元素上而没有$('#timer').countdown();
那么_start()
将仅被调用一次(第一次调用)。
您现在可以通过不同的方式使用新值重置倒计时:
// new value to set = 3600
// Call to the "public" `reset()` function
$('#timer').countdown('reset', 3600);
// Call to the `_setOption()`
$('#timer').countdown({remaining: 3600});
// Call to the `_setOption()`
$('#timer').countdown('option', 'remaining', 3600);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.