Create templates without replacing DOM elements
There are two ways of rendering data on the browser -- templates and declarations.
Templates have HTML with embedded JavaScript. Examples: underscore.js, react.js
# Typical template approach
<script type="text/html" id="template">
<% [1,2,3].forEach(function(x) { %>
<p><%= x %></p>
<% }) %>
</script>
Declarations have JavaScript with embedded HTML, e.g. jQuery, d3.
<script>
[1,2,3].forEach(function(x) { result += '<p>' + x + '</p>' })
</script>
I like the template-based approach. It keeps the focus on the content and away from the logic. G.min.js provides the $().template()
function to simplify template-based rendering
The problem is: re-rendering the template removes the original DOM elements, making it impossible to smoothly animate from the original to the new state. react.js permits this via a virtual DOM, but has too many other constructs (JSX, a framework) that I don't want.
So let's create our own virtual dom. We're trying to mimic the diffhtml library:
- Convert the old DOM and new DOM into virtual trees (html2hscript, for example -- but diffhtml has a cleaner way of doing this.
- Diff the trees
- Apply the patch
This should ideally be how $().template()
works, as long as its dependencies are available.