JSFiddle - React, Tailwind, and code Playground
by fastfasterfastest
HTML
<div>x=<span data-bind="text: x"></span></div>
<div>y=<span data-bind="text: y"></span></div>
CSS
div {
border: 1px solid gray;
padding: .5em;
margin: .5em;
}
div > div
{
border: 1px solid lightgray;
}
button {
display: inline-block;
margin-left: 1em;
}
JavaScript
function ViewModel() {
this.x = ko.observable(0);
this.y = ko.pureComputed(function () {
var readCounter = this.y.readCounter++,
y;
console.log("this.y.read BEGIN (" + readCounter + ")");
if (readCounter < 5){
var x = this.x();
console.log("this.y.read: calling this.x(" + (x + 1) + ")");
this.x(x + 1);
console.log("this.y.read: called this.x(" + (x + 1) + ")");
y = x;
}else{
y = 14;
}
console.log("this.y.read END (" + readCounter + ") - returning " + y);
return y;
}, this);
this.y.readCounter = 0;
}
ko.options.deferUpdates = true;
ko.onError = function (error) {
alert("knockout error\n" + error);
};
// bind viewmodel
var vm = new ViewModel();
ko.applyBindings(vm);