only bind className when the obj has at least 1 fn, also support it html

This commit is contained in:
Bruno Windels 2019-06-16 15:12:54 +02:00
parent 590ed56d68
commit d72a7102b2
2 changed files with 28 additions and 12 deletions

View file

@ -1,17 +1,13 @@
import { setAttribute, text, isChildren, TAG_NAMES } from "./html.js"; import { setAttribute, text, isChildren, classNames, TAG_NAMES } from "./html.js";
function classNames(obj, value) { function objHasFns(obj) {
return Object.entries(obj).reduce((cn, [name, enabled]) => { for(const value of Object.values(obj)) {
if (typeof enabled === "function") { if (typeof value === "function") {
enabled = enabled(value); return true;
} }
if (enabled) { }
return (cn.length ? " " : "") + name; return false;
} else {
return cn;
}
}, "");
} }
/** /**
Bindable template. Renders once, and allows bindings for given nodes. If you need Bindable template. Renders once, and allows bindings for given nodes. If you need
@ -152,7 +148,11 @@ export default class Template {
const isFn = typeof value === "function"; const isFn = typeof value === "function";
// binding for className as object of className => enabled // binding for className as object of className => enabled
if (key === "className" && typeof value === "object" && value !== null) { if (key === "className" && typeof value === "object" && value !== null) {
this._addClassNamesBinding(node, value); if (objHasFns(value)) {
this._addClassNamesBinding(node, value);
} else {
setAttribute(node, key, classNames(value));
}
} else if (key.startsWith("on") && key.length > 2 && isFn) { } else if (key.startsWith("on") && key.length > 2 && isFn) {
const eventName = key.substr(2, 1).toLowerCase() + key.substr(3); const eventName = key.substr(2, 1).toLowerCase() + key.substr(3);
const handler = value; const handler = value;

View file

@ -5,6 +5,19 @@ export function isChildren(children) {
return typeof children !== "object" || !!children.nodeType || Array.isArray(children); return typeof children !== "object" || !!children.nodeType || Array.isArray(children);
} }
export function classNames(obj, value) {
return Object.entries(obj).reduce((cn, [name, enabled]) => {
if (typeof enabled === "function") {
enabled = enabled(value);
}
if (enabled) {
return cn + (cn.length ? " " : "") + name;
} else {
return cn;
}
}, "");
}
export function setAttribute(el, name, value) { export function setAttribute(el, name, value) {
if (name === "className") { if (name === "className") {
name = "class"; name = "class";
@ -29,6 +42,9 @@ export function el(elementName, attributes, children) {
if (attributes) { if (attributes) {
for (let [name, value] of Object.entries(attributes)) { for (let [name, value] of Object.entries(attributes)) {
if (name === "className" && typeof value === "object" && value !== null) {
value = classNames(value);
}
setAttribute(e, name, value); setAttribute(e, name, value);
} }
} }