JSFiddle - React, Tailwind, and code Playground
HTML
<div id="shell" class="fixy"></div>
CSS
#shell {
font-family: monospace;
line-height: 1.5em;
margin-left: 2em;
}
#shell > * {
white-space: pre;
}
#shell .in:before {
content: '>';
margin-right: 1em;
color: #f90;
}
#shell .in:not(:first-child) {
margin-top: 1em;
}
#shell .out {
color: #11f;
}
JavaScript
// magic hackative to display functon execution line-by-line
function echo(intext,showOutput){
intext = intext.trim();
if(intext.length==0)
return;
var outtext = eval(intext);
var shell = document.getElementById('shell');
var line = document.createElement('div');
line.classList.add('in');
line.innerText = intext;
shell.appendChild(line);
if(showOutput) {
line = document.createElement('div');
line.classList.add('out');
line.innerText = outtext;
shell.appendChild(line);
}
}
function functionBody(f) {
var s = f.toString();
return s.slice(s.indexOf('{')+1,s.lastIndexOf('}'));
}
function echoFunction(f) {
var s = functionBody(f);
s.split('\n').map(echo);
}
var f,c;
// the actual thing I want to show you
function setup() {
// wrap up KO observable functions in getters/setters
function F(obs) {
Object.defineProperty(this,'v',{
get: function() {
return obs();
},
set: function(v) {
return obs(v);
}
});
}
// avoid typing the `new` operator
function maker(obs) {
return new F(obs);
}
// f is a number
f = maker(ko.observable(1));
// c is x^2
c = maker(ko.computed({
read: function() {
return f.v*f.v;
},
write: function(v) {
f.v = Math.sqrt(v);
}
}));
}
//setup();
//document.getElementById('setup').innerText = functionBody(setup);
echo(functionBody(setup),false);
// demo lines
echoFunction(function() {
f.v; // value of f
c.v; // value of c
f.v = 3; // change value of f
c.v; // value of c changes!
c.v = 16; // change value of c
f.v; // value of f changes!!
});