Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon
Created December 6, 2018 22:05
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 graphicbeacon/162fe3bdb0d03f34e0b4a534994c9823 to your computer and use it in GitHub Desktop.
Save graphicbeacon/162fe3bdb0d03f34e0b4a534994c9823 to your computer and use it in GitHub Desktop.
A lightweight Virtual DOM implementation in Dart
import 'dart:html';
void main() {
var vApp = createElement('div',
attrs: {
'id': 'app',
},
children: [
'Hello Cat!',
createElement('img',
attrs: {
'src': 'https://media.giphy.com/media/cuPm4p4pClZVC/giphy.gif',
}),
]
);
mount(render(vApp), querySelector('body'));
}
// Builds a map representing an HTML DOM element
createElement(tagName, {attrs = const {}, List children = const []}) => {
'tagName': tagName,
'attrs': attrs,
'children': children
};
// Renders the config into an actual DOM element
renderElem(vNode) {
var $el = document.createElement(vNode['tagName']);
vNode['attrs'].forEach((key, value) {
$el.setAttribute(key, value);
});
for (var child in vNode['children']) {
$el.append(render(child));
}
return $el;
}
// Strategy to determine what to render
render(vNode) {
if (vNode is String) {
return Text(vNode);
}
return renderElem(vNode);
}
// Inserts it in the target element
mount(Element vNode, Element target) {
target.replaceWith(vNode);
return vNode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment