I am relatively new to KO (started 2 days ago) and tried some simple examples. I am currently having a problem with this piece of code.
<div id="idChangeStyle"> <span data-bind="style: { background: GetAge() < 18 ? 'red':'white'}">Enter Your Age:</span> <input type="text" data-bind="value: GetAge"></input> </div>
function ageViewModel() { var self = this; self.age = ko.observable(18); self.GetAge = ko.computed({ read: function () { return self.age(); }, write: function (value) { value = parseInt(String(value).replace(/[^\d]/g, "")); if (isNaN(value)) self.age(18); else self.age(value); } }); }; ko.applyBindings(new ageViewModel(), document.getElementById('idChangeStyle'));
http://jsfiddle.net/WJZqj/
Basically the application accepts one input (age). I use writeable records for parsing input in INTEGER and after parsing, if its NaN I try to set the default value for age to 18. That is, I have a simple logic in html where I change the span background to red, if age is less than 18.
In the normal case, it works fine, that’s when I get into the problem: -
Case 1: Current Input: 18 (initial case) enter *4* then tab
I checked the knockout code to find out what happens when the following code fragment starts: -
if(isNaN(value)) self.age(18);
.. in the next line: -
// Ignore writes if the value hasn't changed if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
both _latestValue and arguments[0] have the same value (18), so they do nothing. Due to the absence of a change in the age value, now the viewmodel property and user interface are not synchronized.
Is it because I'm doing it wrong?