Created
December 6, 2018 22:05
-
-
Save graphicbeacon/162fe3bdb0d03f34e0b4a534994c9823 to your computer and use it in GitHub Desktop.
A lightweight Virtual DOM implementation in Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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