Attr Types
Convert simple types to and from HTML node attributes.
This is useful when building WebComponents.
Note that this only allows simple types (as opposed to complex types), which are typically used in HTML attributes.
See this on how to pass complex data to WebComponents.
Parsing
import AttrTypes from 'attr-types';
AttrTypes.string('asdf')
AttrTypes.number('3')
AttrTypes.array('w,a,s,d')
AttrTypes.bool('')
AttrTypes.bool(null)
const aOfN = AttrTypes.arrayOf(number);
aOfN('1,2,3')
aOfN('1,2,c')
const lOrR = AttrTypes.oneOf(['left', 'right']);
AttrTypes.lOrR('left')
AttrTypes.lOrR('down')
Stringifying
import AttrTypes from 'attr-types';
AttrTypes.number.stringify(3)
AttrTypes.array.stringify(['w', 'a', 's', 'd'])
AttrTypes.bool.stringify(true)
AttrTypes.bool.stringify(false)
const aOfN = AttrTypes.arrayOf(number);
aOfN.stringify([1, 2, 3])
const lOrR = AttrTypes.oneOf(['left', 'right']);
lOrR.stringify('left')
lOrR.stringify('down')
DOM Interaction
To get the value of an attribute (e.g. inside attributeChangedCallback
):
const attrType = getTypeFor(attrName);
const value = attrType(el.getAttribute(attrName));
To reflect a changed property in the node attributes, use:
const attrType = getTypeFor(attrName);
const attr = attrType.stringify(value);
if (attr == null) {
el.removeAttribute(attrName);
} else {
el.setAttribute(attrName, attr);
}
AttrTypes is used in the wild by hy-drawer and hy-push-state.