only bind className when the obj has at least 1 fn, also support it html
This commit is contained in:
parent
590ed56d68
commit
d72a7102b2
2 changed files with 28 additions and 12 deletions
|
@ -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) {
|
||||
return Object.entries(obj).reduce((cn, [name, enabled]) => {
|
||||
if (typeof enabled === "function") {
|
||||
enabled = enabled(value);
|
||||
function objHasFns(obj) {
|
||||
for(const value of Object.values(obj)) {
|
||||
if (typeof value === "function") {
|
||||
return true;
|
||||
}
|
||||
if (enabled) {
|
||||
return (cn.length ? " " : "") + name;
|
||||
} else {
|
||||
return cn;
|
||||
}
|
||||
}, "");
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
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";
|
||||
// binding for className as object of className => enabled
|
||||
if (key === "className" && typeof value === "object" && value !== null) {
|
||||
if (objHasFns(value)) {
|
||||
this._addClassNamesBinding(node, value);
|
||||
} else {
|
||||
setAttribute(node, key, classNames(value));
|
||||
}
|
||||
} else if (key.startsWith("on") && key.length > 2 && isFn) {
|
||||
const eventName = key.substr(2, 1).toLowerCase() + key.substr(3);
|
||||
const handler = value;
|
||||
|
|
|
@ -5,6 +5,19 @@ export function isChildren(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) {
|
||||
if (name === "className") {
|
||||
name = "class";
|
||||
|
@ -29,6 +42,9 @@ export function el(elementName, attributes, children) {
|
|||
|
||||
if (attributes) {
|
||||
for (let [name, value] of Object.entries(attributes)) {
|
||||
if (name === "className" && typeof value === "object" && value !== null) {
|
||||
value = classNames(value);
|
||||
}
|
||||
setAttribute(e, name, value);
|
||||
}
|
||||
}
|
||||
|
|
Reference in a new issue