pabrams
pabrams

Reputation: 1164

Knockout observable behavior

My question is why my two data-bound input fields are behaving differently when I clear them, even though as far as I can tell they are set up the same way as calculated observables in knockout.

Using this fiddle: http://jsfiddle.net/ya7eF/167/

The 'min' field is working properly, the 'hrs' field is not. To reproduce my problem, follow the steps below. When I remove text from Duration 'hrs' field, I want to understand why it is not replaced with zero on blur, like the min field.

  1. Delete text ('30') from second Duration ('min') text field, then lose focus on that field. Empty string gets replaced with zero, and other computed observables (end time) are updated. As desired.
  2. Re-run the fiddle.
  3. Delete text ('0') from Duration 'hrs' text field
  4. Blur 'hrs'
  5. Nothing happens; the 'read' method for the computed observable for hours never even gets called. I can't figure out what the difference is between the two observables.

Upvotes: 0

Views: 1143

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

In the second case the value of the Duration observable did not actually change. When an observable's value is set to its current value, then no notifications are sent out to subscribers. This means that the read functions of your computed observables are not triggered.

One technique to deal with this concern is to use an observable's valueHasMutated function to ensure that notifications are sent out. To avoid multiple notifications, you could do something like:

        if (totalMinutes !== self.Duration()) {
            self.Duration(totalMinutes);
        }
        self.Duration.valueHasMutated();

Here is your sample updated: http://jsfiddle.net/rniemeyer/ya7eF/168/

Upvotes: 1

Related Questions