Forcing update of a throttled computed property
Asked Answered
S

1

6

I have a form with a text input bound to computed property (containing a time). After a user enters a value, it is parsed into a integer value containing the total minutes.

Since this is not a trivial function (there are many ways of formatting time), the property has a Throttle Extender.

This all works fine, the problem is when the user enters a value and immediately hits a save button, obviously the throttled value is not evaluated yet.

self.totalMinutes = ko.observable(0);
self.totalMinutesValue = ko.computed({
    read: function() { 
        return MinutesToFormat(self.totalMinutes()); 
    } 
    write: function(value) { 
        self.totalMinutes(FormatToMinutes(value)); 
    } 
}).extend({ throttle: 250 });

self.Save = function() {
    // Send self.totalMinutes() to server, need to ensure the throttled 
    // computed has been written.
}

Is there a simple way to force the property to update immediately from the send method? I could add a setTimeout but that is of course far from ideal.

Sangsanger answered 1/5, 2014 at 7:2 Comment(1)
I have not used throttle much but in 3.1 i believe it is recommended that you instead use the rateLimit extender. Maybe this will solve the issue? - knockmeout.net/2014/03/knockout-3-1-released.htmlConjure
C
4

It seems the rateLimiter could infact solve this problem.

http://knockoutjs.com/documentation/rateLimit-observable.html

"Writes to observables are not delayed; the observable’s value is updated right away. For writable computed observables, this means that the write function is always run right away.

All change notifications are delayed, including when calling valueHasMutated manually. This means you can’t use valueHasMutated to force a rate-limited observable to notify an un-changed value.

The default rate-limit method is different from the throttle algorithm. To match the throttle behavior, use the notifyWhenChangesStop method."

Evaluation of a rate-limited computed observable isn’t rate-limited; it will re-evaluate if you read its value.

Conjure answered 1/5, 2014 at 7:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.