using valueHasMutated

by vintharas

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.1.0.js"></script>
<!-- by Ryan Niemeyer -->
<div>Enter 11.3 and then 11.4 after commenting out the valueHasMutated call</div>
<input data-bind="value: formattedValue" />

JavaScript

var ViewModel = function() {
  this.value = ko.observable(10);
  
  //ensure that a value is rounded for storing  
  this.formattedValue = ko.computed({
    read: this.value,
    write: function(newValue) {
        var value =  isNaN(newValue) ? 0 : parseFloat(newValue).toFixed(0),
            current = this.value();            
        
        //check if the parsed value is different than our current
        if (value !== current) {
           this.value(value);   
        }
        else {
           //check if the input is different than the current value (need to notify UI)
            if (current !== parseFloat(newValue)) {
                this.value.valueHasMutated();
            }                
        }
    }
  }, this);    
};

ko.applyBindings(new ViewModel());