Skip to content

Instantly share code, notes, and snippets.

@brainrake
Created January 12, 2017 22:08
Show Gist options
  • Save brainrake/6c814fa51e5d2fcbcea41d8f4f73ca01 to your computer and use it in GitHub Desktop.
Save brainrake/6c814fa51e5d2fcbcea41d8f4f73ca01 to your computer and use it in GitHub Desktop.
model-view-update in js
<html>
<body>
<script src="https://gitcdn.xyz/repo/Matt-Esch/virtual-dom/master/dist/virtual-dom.js"></script>
<script>
var h = require('virtual-dom/h');
var diff = require('virtual-dom/diff');
var patch = require('virtual-dom/patch');
var createElement = require('virtual-dom/create-element');
model = 0
view = model =>
h('div', {},
[ h('button', { onclick : () => send("Increment") }, [ "+" ] )
, h('div', {}, [ String(model) ])
, h('button', { onclick : () => send("Decrement") }, [ "-" ] )
])
update = (msg, model) => {
if (msg == "Increment") {
return model + 1;
} else if (msg == "Decrement") {
return model - 1;
} else {
console.error("Invalid message: ", msg);
return model;
}
}
send = msg => {
model = update(msg, model)
var newTree = view(model)
var patches = diff(tree, newTree)
rootNode = patch(rootNode, patches)
tree = newTree
}
tree = view(model)
rootNode = createElement(tree)
document.body.appendChild(rootNode)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment