Observable array

by wwwroot

HTML

Price: <input data-bind="value: price.formatted" /><br>
Tax: <input data-bind="value: tax.formatted" /><br>
Total: <span data-bind="text: total.formatted"></span>

JavaScript

ko.observable.fn.withCurrencyFormat = function(precision) {
    var observable = this;
    observable.formatted = ko.computed({
        read: function (key) {
            return (observable()).toFixed(precision);
        },
        write: function (value) {
            value = parseFloat(value.replace(/[^\.\d]/g, ""));
            observable(isNaN(value) ? null : value); // Write to underlying storage 
        }        
    }); 

    return observable;
};


function revenueStream() {
  var self = this;
  self.price = ko.observable(0).withCurrencyFormat(2);
  self.tax = ko.observable(0).withCurrencyFormat(2);
    self.total = ko.computed(function(){
        return self.price() + self.tax();
    }).withCurrencyFormat(2);
}
    
ko.applyBindings(new revenueStream());