Skip to content

Instantly share code, notes, and snippets.

@rightfold
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rightfold/447c45c13b17a8b29b61 to your computer and use it in GitHub Desktop.
Save rightfold/447c45c13b17a8b29b61 to your computer and use it in GitHub Desktop.
{
"name": "downtime",
"dependencies": {
"virtual-dom": "~1.3.0",
"lenses": "DrBoolean/lenses",
"rxjs": "~2.4.1"
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Downtime</title>
<script src="bower_components/virtual-dom/dist/virtual-dom.js"></script>
<script src="bower_components/lenses/dist/lenses.browser.js"></script>
<script src="bower_components/rxjs/dist/rx.all.js"></script>
<script src="main.js"></script>
</head>
<body>
</body>
</html>
function input(lens) {
return h('input', {
oninput: function(ev) {
setState(Lenses.set(L.name, ev.target.value, getState()));
},
value: Lenses.view(lens, getState())
});
}
function button(onclick, body) {
return h('button', { onclick: onclick }, body);
}
var L = Lenses.makeLenses(['debt', 'name']);
function render() {
return h('div', {}, [
h('strong', {}, ['Debt: $' + getState().debt.toFixed(2)]),
input(L.name),
button(function() { setState(Lenses.set(L.debt, 0, getState())) }, [
'reset debt'
]),
h('strong', {}, ['Hello, ' + getState().name + '!'])
]);
}
addEventListener('load', function() {
setState({ debt: 0, name: 'world' });
Rx.Observable.interval(1000)
.subscribe(function() {
setState({ debt: getState().debt + Math.random() * 2, name: getState().name });
});
});
var h = virtualDom.h;
var state = null;
var tree = null;
var node = null;
function getState() {
return state;
}
function setState(newState) {
state = newState;
if (tree === null) {
tree = render();
node = virtualDom.create(tree);
document.body.appendChild(node);
} else {
var newTree = render();
var patches = virtualDom.diff(tree, newTree);
virtualDom.patch(node, patches);
tree = newTree;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment