JSFiddle - React, Tailwind, and code Playground
HTML
<div>Input binding <input data-bind="value: val" /></div>
<div>Text biding <span data-bind="text: val"></span></div>
<div>Model state</div>
<div data-bind="text: ko.toJSON($data)"></div>
JavaScript
var toViewBindingHandlers = {
value: true,
text: true
};
var toViewPreprocessor = function(value) {
return "(" + value + ").toView || " + value;
};
for(var bindingHandler in toViewBindingHandlers) {
ko.bindingHandlers[bindingHandler].preprocess = toViewPreprocessor;
}
ko.extenders.numeric = function(observable, options) {
var textValue = null;
observable.toView = ko.computed({
write: function(value) {
var textValueMutated = value != textValue;
textValue = value;
var parsed = Number.parseFloat(value);
if(!isNaN(parsed)) {
observable(parsed);
} else {
observable(null);
if(textValueMutated) {
observable.notifySubscribers();
}
}
},
read: function() {
var value = observable();
if(value == null) {
return textValue;
}
return value.toLocaleString(); //This can be replaced with for example the Globalize plugin
}
});
return observable;
};
ko.applyBindings({ val: ko.observable().extend({ numeric: true }) });