Reevaluate a computed function every x seconds in KnockoutJS

人盡茶涼 提交于 2019-12-24 22:31:55

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!