每隔X秒在KnockoutJS中重新评估计算函数 [英] Reevaluate a computed function every x seconds in KnockoutJS
本文介绍了每隔X秒在KnockoutJS中重新评估计算函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是否可以每1000毫秒执行一次计算函数,以在UI中每显示1000毫秒获得一个新的时间跨度值?
Can I execute the computed function say every 1000 ms to get a new timespan value every 1000 ms displayed in my UI ?
self.timespan = ko.computed(function() {
return self.orderTime() + " " + new Date();
});
推荐答案
Wrap your new Date()
in a timer observable, and update it every 1000 ms using setInterval
, for example like this:
function myViewModel() {
var self = this;
self.orderTime = ko.observable(new Date(2013,1,1,12,0,0));
self.timer = ko.observable(new Date());
self.timespan = ko.computed(function() {
return self.orderTime() + " " + self.timer();
});
window.setInterval(function() { self.timer(new Date()); }, 1000);
}
ko.applyBindings(new myViewModel());
如果愿意,还可以始终将timer
可观察到的内容设为ViewModel范围的私有对象,具体取决于您是否要直接公开它.
If you want you could also always make the timer
observable private to the ViewModel's scope, depending on whether you want to expose it directly or not.
有关演示,请参见此小提琴.
这篇关于每隔X秒在KnockoutJS中重新评估计算函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文