gpt4 book ai didi

javascript - jQuery 小部件工厂 _destroy 方法

转载 作者:行者123 更新时间:2023-12-02 17:53:36 25 4
gpt4 key购买 nike

我正在尝试创建一个计时器小部件,该小部件可以用秒数进行初始化,然后通过使用新的倒计时“秒数”进行新调用来随时重置。到目前为止,我已经有了这个,它可以很好地创建计时器并倒计时。

我想做的是首先在 _create 方法中调用 _destroy 方法来删​​除元素上已有的计时器,并使用 window.clearInterval 来停止重新添加计时器。 this.interval 在 _start 方法中设置,然后在 _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() 函数:

  • 设置新的剩余值,
  • 清除间隔,
  • 然后调用_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);

关于javascript - jQuery 小部件工厂 _destroy 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21159493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com