Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tokland
Last active March 19, 2017 21:13
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 tokland/6f6344d3e168b8ceee158473d6080078 to your computer and use it in GitHub Desktop.
Save tokland/6f6344d3e168b8ceee158473d6080078 to your computer and use it in GitHub Desktop.
Simple demo using immutable states with virtual-dom
<html xmlns="http://www.w3.org/1999/xhtml" lang="es" xml:lang="es">
<head>
<title>Simple functional app using VirtualDom</title>
<script src="http://wzrd.in/standalone/virtual-dom@latest"></script>
<script src="simple_virtual_dom.js"></script>
<script src="incrementor.js"></script>
</head>
<body>
<div id="incrementor">
App placeholder
</div>
</body>
</html>
var html = virtualDom.h;
function render(model, toEvent) {
return (
html('div', {}, [
html("button", {onclick: toEvent(incrementCounter)}, ["Increment"]),
html("span", {}, [String(model.count)]),
html('input', {placeholder: "This field will not be overwritten on view renders", size: 50})
])
);
}
function incrementCounter(ev, model) {
return {count: model.count + 1};
}
function runApp() {
var app_el = document.getElementById("incrementor");
var initialModel = {count: 0};
var app = App(app_el, initialModel, render);
}
document.addEventListener('DOMContentLoaded', runApp, false);
function App(appEl, initialModel, render) {
var toEvent = function(eventCallback) {
return function(ev) {
var newModel = eventCallback(ev, state.model);
state = _getNewState(state, newModel, toEvent);
};
};
var state;
var tree = render(initialModel, toEvent);
var rootNode = virtualDom.create(tree);
state = {tree: tree, render: render, rootNode: rootNode, model: initialModel};
appEl.innerHTML = "";
appEl.appendChild(rootNode);
return state;
}
function _getNewState(state, newModel, event) {
var newTree = state.render(newModel, event);
var newRootNode = _updateDOM(state.rootNode, state.tree, newTree);
return {model: newModel, render: state.render, tree: newTree, rootNode: newRootNode};
}
function _updateDOM(rootNode, originalTree, newTree) {
var patches = virtualDom.diff(originalTree, newTree);
return virtualDom.patch(rootNode, patches);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment