I've been working my way through the KnockoutJS documentation
and tried to modify example 3 of the "Writeable computed observables"
section in this
page.
The example basically shows a textbox and displays a message if the
user enters a non-numeric value to the textbox. I tried to modify the
code so that the textbox has a pink background when the message appears.
The problem is when you enter a invalid value the textbox turns pink
as expected but the value you entered is replaced with what was
originally there. I have no idea why this behavior is occurring since
everything worked fine before I added the style binding to get the pink
background. Try removing the style binding and notice how the behavior
changes when you enter an invalid value.
What's going on?
The code is below or try out this
jsfiddle.
<p>
Enter a numeric value:
<input data-bind="value: attemptedValue
,style: {backgroundColor: lastInputWasValid() ?
'transparent' :
'pink' }"/>
</p>
<div data-bind="visible: !lastInputWasValid()">That's not a number!</div>
function MyViewModel() {
this.acceptedNumericValue = ko.observable(123);
this.lastInputWasValid = ko.observable(true);
this.attemptedValue = ko.computed({
read: this.acceptedNumericValue,
write: function (value) {
if (isNaN(value))
this.lastInputWasValid(false);
else {
this.lastInputWasValid(true);
this.acceptedNumericValue(value); // Write to underlying storage
}
},
owner: this
});
}
ko.applyBindings(new MyViewModel());
EDIT: Here's another
fiddle
with the style binding removed. Try appending the letter 'a' and taking
focus out of the textbox. Notice how the letter 'a' stays there. Try
that with the original
fiddle textbox and notice how it is removed. The only change between the two fiddles is the presence of the style binding.