all repos — h3 @ 445a314facea9c5e0d92f13ab4c88708e09d87db

A tiny, extremely minimalist JavaScript microframework.

Added utility methods;
h3rald h3rald@h3rald.com
Fri, 10 Apr 2020 12:30:59 +0200
commit

445a314facea9c5e0d92f13ab4c88708e09d87db

parent

8389fe53be654cd3dccf84c38b121e1c389a75f6

2 files changed, 26 insertions(+), 8 deletions(-)

jump to
M example/assets/js/app.jsexample/assets/js/app.js

@@ -32,10 +32,7 @@

// Actual DOM creation/updateing self.update = () => { self.save(); - const newTree = self.render(); - /*self.view.update({ node: self.container.childNodes[0], vnode: newTree }); - self.view = newTree;*/ - self.view.update({ vnode: newTree }); + self.view.update({ vnode: self.build() }); }; // UI Methods

@@ -93,7 +90,7 @@ // Filtering function for todo items

self.filterTodos = ({ text }) => text.match(self.filter); // Main rendering function (creates virtual dom) - self.render = () => { + self.build = () => { const hash = window.location.hash; self.filteredTodos = self.todos.filter(self.filterTodos); if (hash.match(/page=(\d+)/)) {

@@ -144,7 +141,7 @@ ]);

}; self.init = () => { self.load(); - self.view = self.render(); + self.view = self.build(); self.container.appendChild(self.view.render()); }; // Initialize...
M h3.jsh3.js

@@ -1,5 +1,5 @@

// Basic object equality -function equal(obj1, obj2) { +export const equal = (obj1, obj2) => { if ( (obj1 === null && obj2 === null) || (obj1 === undefined && obj2 === undefined)

@@ -54,8 +54,29 @@ }

return checkProperties(o1, o2) && checkProperties(o2, o1); } +/** + * Creates an updatable region within a page, identified by a unique ID. + * @param {Function} builder A function returning a VNode object. + * @returns {Array[Element, Function]} The DOM element resulting by rendering the built VNode and a function used to update (rebuild) the element. + */ +export const region = (builder) => { + const vnode = builder(); + if (!vnode.id) { + throw 'No ID specified for region VNode.'; + } + return [vnode.render(), () => vnode.update(builder())]; +} +/** + * Mounts a VNode and renders it as a child of an existing DOM Element. + * @param {string} id A unique ID of of an existing DOM Element. + * @param {VNode} vnode The VNode to mount as child of the specified DOM element. + */ +export const mount = (id, vnode) => { + document.getElementById(id).appendChild(vnode.render()); +} + // Virtual Node Implementation with HyperScript-like syntax -class VNode { +export class VNode { constructor(...args) { this.element = null; this.attributes = {};