问题
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();
});
回答1:
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());
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.
See this fiddle for a demo.
来源:https://stackoverflow.com/questions/16997638/reevaluate-a-computed-function-every-x-seconds-in-knockoutjs