extract argument detection for el and use it in both html and Template

This commit is contained in:
Bruno Windels 2019-06-15 17:50:54 +02:00
parent 03df472c53
commit 95e1d55b97
2 changed files with 18 additions and 12 deletions

View file

@ -1,4 +1,4 @@
import { setAttribute, text, TAG_NAMES } from "./html.js";
import { setAttribute, text, isChildren, TAG_NAMES } from "./html.js";
function classNames(obj, value) {
@ -130,14 +130,9 @@ export default class Template {
}
el(name, attributes, children) {
if (attributes) {
// valid attributes is only object that is not a DOM node
// anything else (string, fn, array, dom node) is presumed
// to be children with no attributes passed
if (typeof attributes !== "object" || !!attributes.nodeType || Array.isArray(attributes)) {
children = attributes;
attributes = null;
}
if (attributes && isChildren(attributes)) {
children = attributes;
attributes = null;
}
const node = document.createElement(name);

View file

@ -1,5 +1,9 @@
// DOM helper functions
export function isChildren(children) {
return typeof children !== "object" || !!children.nodeType || Array.isArray(children);
}
export function setAttribute(el, name, value) {
if (name === "className") {
name = "class";
@ -14,13 +18,20 @@ export function setAttribute(el, name, value) {
}
}
export function el(elementName, attrs, children) {
export function el(elementName, attributes, children) {
if (attributes && isChildren(attributes)) {
children = attributes;
attributes = null;
}
const e = document.createElement(elementName);
if (typeof attrs === "object" && attrs !== null) {
for (let [name, value] of Object.entries(attrs)) {
if (attributes) {
for (let [name, value] of Object.entries(attributes)) {
setAttribute(e, name, value);
}
}
if (children) {
if (!Array.isArray(children)) {
children = [children];