KnockoutJS Watchdog
-
Comments:
- here.
I first discovered KnockoutJS many years ago. It’s a really neat way of managing dependencies between values, and also updating HTML accordingly. Recently, I rewrote my fronius-dashboard to use a Quart app and KnockoutJS instead of a Phoenix LiveView, as the latter was much harder to build (and dependency changes seem to break that fairly frequently).
One thing I did notice is that from time to time I’ll come back to a pinned tab version of the app and it will no longer be updating. I’m not sure exactly why that is, but it seems to be connected still (the EventSource object says it is still connected, anyway).
So, I thought maybe a watchdog process would be in order.
Basically, if there are no updates for a certain period of time, then it should just reload the page.
KnockoutJS doesn’t have anything like this built in, but it does have the facility to throttle updates, and and specifically, to use the “only update when changes stop” facility. As such, we can build a watchdog fairly easily using just that:
let watchdog = ko.computed(() => viewModel.grid()).extend({
rateLimit: {
timeout: 10000,
method: "notifyWhenChangesStop"
}
});
watchdog.subscribe(() => {
document.location.reload();
});
In this case, I have one value that will almost certainly update every second (or more frequently than this), called grid
.
If there are no updates for 10 seconds, then it will reload the page.
I’m not sure that this will actually solve my problem though - I suspect that the stoppage happens because the browser tab is not frontmost, and the JS is suspended, and doesn’t un-suspend properly. Time will tell, I guess.