JSFiddle - React, Tailwind, and code Playground

by rniemeyer

HTML

<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<p> The read function does get executed, but it's return value is not used at all. Notice there is no dollar sign added when displaying the value in the text boxes.</p>
<br />
<p>The write function works perfectly, it strips the dollar sign, converts it from a string to a number, and rounds the amount to 2 decimal places, storing the result in the observable. The text fields update with the rounded value, only if the value entered and the rounded value are not equivalent. If you enter "34.0000000" the observable value will be 34, but the text box will still display "34.0000000"</p>
<br />

Amount 1: <input type="text" data-bind="amountValue: amount1" />
<br />
Amount 2: <input type="text" data-bind="amountValue: amount2" />

<br /><br />

Amount 1 value: <span data-bind="text: amount1"></span>
<br />
Amount 2 value: <span data-bind="text: amount2"></span>

JavaScript

ko.bindingHandlers.amountValue = {
  init: function (element, valueAccessor, allBindingsAccessor) {
    var underlyingObservable = valueAccessor();

    var interceptor = ko.computed({
      read: function () {
        // this function does get called, but it's return value is not used as the value of the textbox.
        // the raw value from the underlyingObservable, or the actual value the user entered is used instead, no   
        // dollar sign added. It seems like this read function is completely useless, and isn't used at all
        return "$" + underlyingObservable();
      },

      write: function (newValue) {
        var current = underlyingObservable(),
            valueToWrite = Math.round(parseFloat(newValue.replace("$", "")) * 100) / 100;

        if (valueToWrite !== current) {
          // for some reason, if a user enters 20.00000 for example, the value written to the observable
          // is 20, but the original value they entered (20.00000) is still shown in the text box.
          underlyingObservable(valueToWrite);
        } else {
          if (newValue !== current.toString())
            underlyingObservable.valueHasMutated();
        }
      }
    });

      ko.applyBindingsToNode(element, { value: interceptor });
  }
};

var viewModel = {
  amount1: ko.observable(22.45),
  amount2: ko.observable(143.56)
};

ko.applyBindings(viewModel);