developarvin
developarvin

Reputation: 5087

KnockoutJS - Recalculate computed values with a set time interval

I have this code here

self.timestamp = ko.observable(data.timestamp);
self.dateFromNow = ko.computed(function ()
{
    return moment(self.timestamp()).fromNow();
}, self);

self.timestamp is simply a unix timestamp

self.dateFromNow looks something like 44 years ago or 1 minute ago

My goal is for self.dateFromNow to recompute every set time interval.

These properties are bound to HTML <time> elements but I don't want to do the recomputation by using JS/jQuery to go over the elements and recompute. I think a better way would be just to simply recalculate the values in KnockoutJS every set time interval and let KO update the markup.

Is there a way to do this in KnockoutJS?

UPDATE: What I did was something like this in lieu of the poster's answer

setInterval(function() {
  $.each(self.foo(), function(index, item) {
    item.timestamp.notifySubscribers();
  });
}, 60 * 1000); // 60 * 1000 milsec

Upvotes: 2

Views: 1225

Answers (2)

PW Kad
PW Kad

Reputation: 14995

Another way to handle this would be to re-evaluate the computeds whenever another observable changes value, which changes on an interval. Sound crazy?

var fireEvaluations = ko.observable(0);

// Somewhere after the DOM is ready
setInterval(function () {
    fireEvaluations(fireEvaluations() + 1);
}, 6000);

var someOtherObservable = ko.computed(function () {
    // Subscribe to the triggering observable
    if (fireEvaluations()) { }
    // Do your real code
});

Now all computeds which have something like if (fireEvaluations()) { } will re-evaluate once that value changes.

Upvotes: 3

Matt Burnell
Matt Burnell

Reputation: 2796

Not built into knockout, no (at least, not as far as I know). It has a mechanism (throttling) that limits how often view model changes are propagated through, but obviously that's not what you're after. Arguably you should have a member on your view model that you bind through to your element, and then it's your responsibility to update your view model periodically.

Upvotes: 1

Related Questions