JSFiddle - React, Tailwind, and code Playground
by jiggle
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>
<p>Enter a numeric value: <input data-bind="value: attemptedValue"/></p>
<div data-bind="visible: !lastInputWasValid()">That's not a number!</div>
<span data-bind="text:lastValue()"></span>
JavaScript
function MyViewModel() {
this.acceptedNumericValue = ko.observable(123);
this.lastInputWasValid = ko.observable(true);
this.lastValue = ko.observable('test');
this.testFunc = function(){
alert(this.lastValue());
}
this.attemptedValue = ko.computed({
read: this.acceptedNumericValue,
write: function (value) {
this.lastValue(value);
if (isNaN(value))
this.lastInputWasValid(false);
else {
this.lastInputWasValid(true);
this.acceptedNumericValue(value); // Write to underlying storage
}
this.testFunc();
},
owner: this,
});
}
var vm = new MyViewModel();
ko.applyBindings(vm);
console.log(vm.attemptedValue);
vm.attemptedValue('test');